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

1

2 Answers 2

38

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?

Sign up to request clarification or add additional context in comments.

1 Comment

G! that's working perfect! thank you so muuuuucccch! Mr. Sebastian! YOU DA REAL MVP!!!
3

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>

3 Comments

thanks Nitin, your Method also working! really thank you! you are nice guy.!
downvoted. requiring jquery for something so basic is overkill.
As I mentioned if it is required to focus to div at runtime. And does it still overkills if jquery is already being used?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.