Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript Focus on DIV Element not working on chrome

Tags:

javascript

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

like image 709
Ching Ching Avatar asked Feb 20 '16 13:02

Ching Ching


2 Answers

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?

like image 174
Sebastien Daniel Avatar answered Sep 25 '22 14:09

Sebastien Daniel


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>
like image 44
Nitin Garg Avatar answered Sep 22 '22 14:09

Nitin Garg