Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 438
Jimesh Gajera Avatar asked Jun 14 '12 09:06

Jimesh Gajera


People also ask

Can we focus on a div jQuery?

The focus() is an inbuilt method in jQuery which is used to focus on an element. The element get focused by the mouse click or by the tab-navigating button. Here selector is the selected element. Parameter: It accepts an optional parameter “function” which specifies the function to run when the focus event occurs.

Can you set focus on a div?

Yes - this is possible. In order to do it, you need to assign a tabindex... A tabindex of 0 will put the tag "in the natural tab order of the page".


2 Answers

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);
like image 194
Anthony Grist Avatar answered Oct 11 '22 14:10

Anthony Grist


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.

like image 21
LukeAmerica2020 Avatar answered Oct 11 '22 13:10

LukeAmerica2020