Ching Ching
Ching Ching

Reputation: 1049

Javascript Focus on DIV Element not working on chrome

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

Upvotes: 11

Views: 21083

Answers (2)

Nitin Garg
Nitin Garg

Reputation: 896

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>

Upvotes: 3

Sebastien Daniel
Sebastien Daniel

Reputation: 4778

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?

Upvotes: 38

Related Questions