简体   繁体   中英

focus on page load (works if refreshed)

How can I make my page focus automatically on the field

        <script>
    function focus(event) {
            document.getElementById('keywords').focus();
    }
</script>


<BODY onload="focus(event)"></body>

appears to work but only if i refresh the page is there a way to make it focus automatically on the page load.

Just use the autofocus attribute, no javascript needed for this ?

<input id="keywords" autofocus="autofocus" />

There doesn't seem to be anything wrong with the code you have, so there must be something else going on if it's not working.

First include jQuery, then:

$(document).ready(function(){
    $('#keywords').focus();
})

$( "#keywords" ).focus(function() {
  alert( "Handler for .focus() called." );
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM