how to set focus on a div using javascript or jquery when # already added in url?

Jimesh Gajera picture Jimesh Gajera · Jun 14, 2012 · Viewed 43k times · Source

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.

Answer

Anthony Grist picture Anthony Grist · Jun 14, 2012

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);