Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to scroll to an element in jQuery?

I have done the following code in JavaScript to put focus on the particular element (branch1 is a element),

document.location.href="#branch1"; 

But as I am also using jQuery in my web app, so I want to do the above code in jQuery. I have tried but don't know why its not working,

$("#branch1").focus(); 

The above jquery (focus()) code is not working for div, whereas If i am trying the same code with textbox, then its working,

Please tell me, how can I put focus on a div elemnt using jQuery?

Thanks!

like image 938
djmzfKnm Avatar asked Feb 01 '09 06:02

djmzfKnm


People also ask

How do I scroll to a specific div?

The scrollIntoView method: The scrollIntoView() is used to scroll to the specified element in the browser. Example: Using scrollIntoView() to scroll to an element.

How can use scroll event in jQuery?

jQuery scroll() MethodThe scroll event occurs when the user scrolls in the specified element. The scroll event works for all scrollable elements and the window object (browser window). The scroll() method triggers the scroll event, or attaches a function to run when a scroll event occurs.

What is $( window scrollTop ()?

The scrollTop() method sets or returns the vertical scrollbar position for the selected elements. Tip: When the scrollbar is on the top, the position is 0. When used to return the position: This method returns the vertical position of the scrollbar for the FIRST matched element.


2 Answers

For my problem this code worked, I had to navigate to an anchor tag on page load :

$(window).scrollTop($('a#captchaAnchor').position().top); 

For that matter you can use this on any element, not just an anchor tag.

like image 161
Banning Avatar answered Oct 12 '22 05:10

Banning


Like @user293153 I only just discovered this question and it didn't seem to be answered correctly.

His answer was best. But you can also animate to the element as well.

$('html, body').animate({ scrollTop: $("#some_element").offset().top }, 500); 
like image 45
User123342234 Avatar answered Oct 12 '22 05:10

User123342234