11

Hi i want to Focus on div immediately after page load. it's working perfect on Firefox, but not on chrome, it's not working. this is my code :

https://jsfiddle.net/9yb2boxn/

document.getElementById("focusme").focus();
#focusme {width:400px; height:100px; overflow-y:scroll; }
<div id="focusme">
  focus me focus me focus me focus me  focus me focus me focus me focus me  focus me focus me focus me focus me focus me focus me focus me focus me focus me focus me focus me focus me focus me focus me focus me focus me focus me focus me focus me focus me focus me focus me focus me focus me
</div>

in Firefox when i run this code and i Press Down Arrow on keyboard, the div scrolling down. but not on chrome. why this problem occure?

i already try

setTimeout(function() {

   document.getElementById("focusme").focus();

}, 1); 

still not working.

please help. thanks

Ching Ching
  • 1,029
  • 4
  • 19
  • 33
  • Possible duplicate of [Is it possible to focus on a
    using javascript focus() function?](http://stackoverflow.com/questions/3656467/is-it-possible-to-focus-on-a-div-using-javascript-focus-function).
    – Michał Perłakowski Feb 20 '16 at 13:07

2 Answers2

34

If you want to make a non-focusable element focusable, you must add a tabindex attribute to it:

<div id="focusme" tabindex="1"></div>

Also, you can use the ID to reach it with the location hash. See the answer to your question here: Is it possible to focus on a <div> using javascript focus() function?

Community
  • 1
  • 1
Sebastien Daniel
  • 4,649
  • 3
  • 19
  • 34
4

if you want to set focus to div through javascript you can use below code

$("#focusme").attr("tabindex",-1).focus();

Hope this helps you.

 $("#focusme").attr("tabindex",-1).focus();
#focusme {width:400px; height:100px; overflow-y:scroll; }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"></script>
<div id="focusme">
  focus me focus me focus me focus me  focus me focus me focus me focus me  focus me focus me focus me focus me focus me focus me focus me focus me focus me focus me focus me focus me focus me focus me focus me focus me focus me focus me focus me focus me focus me focus me focus me focus me
</div>
Nitin Garg
  • 888
  • 6
  • 7