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!


Solution 1:

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.

Solution 2:

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

Solution 3:

You can extend jQuery functionalities like this:

jQuery.fn.extend({
scrollToMe: function () {
    var x = jQuery(this).offset().top - 100;
    jQuery('html,body').animate({scrollTop: x}, 500);
}});

and then:

$('...').scrollToMe();

easy ;-)