15

I want to set focus on particular div using jquery or javascript. i have just use document.getElementById("pack_0").focus(); in that 'pack_0' is my div id but it doesn't work. I notice that '#' is already added in my url because of some popup coding, so my url is 'http://localhost/website/book#'

So, can any one help me for force fully focus on div when # in url?

Thanks in advance.

Jimesh Gajera
  • 612
  • 1
  • 11
  • 32

3 Answers3

28

From the question, I think what you actually mean by "focus the div" is "change the window's vertical scroll position so the div is visible". If that is the case, you can use the following bit of jQuery code:

$(window).scrollTop($('#pack_0').offset().top);
Anthony Grist
  • 38,173
  • 8
  • 62
  • 76
  • Used `scrollTop` instead of `focus` because `focus` behaved differently in Firefox. Using `focus`, Firefox doesn't center the `DIV` if it is already half showing. Chrome always centered the `DIV`. `scrollTop` behaved the same on both browsers. – jpllosa Jul 13 '21 at 09:34
10

Anthony Grist's assumption is likely correct in your case. However, it may help others searching on this topic to know that if the desired object of focus is a DIV, that DIV should have a tabindex set, e.g., tabindex="9999". Otherwise, most browsers will not assign the focus.

LukeAmerica2020
  • 311
  • 4
  • 6
9

To set focus to div first we need to define tabindex for particular div like as below

<div class="leftbar-btn-module" tabindex="-1">'Content'</div>

And jquery to set focus

jQuery(".leftbar-btn-module").attr("tabindex",-1).focus();
Digisha
  • 355
  • 3
  • 5