jquery scroll to form input

10,593

When focusing an element, the browser scrolls to that element, messing up your animation.

Place the focus in the animations callback to avoid it.

$(document).ready(function () {
    $("#get-started").click(function (e) {
        e.preventDefault();
        $('html, body').animate({
            scrollTop: $("#get-risk").offset().top
        }, 2000, function() {
            $("#get-started-apply-now-form [name='last_name']").focus();
        });
    });
});
Share:
10,593
Jared Michael Czerew
Author by

Jared Michael Czerew

Updated on June 26, 2022

Comments

  • Jared Michael Czerew
    Jared Michael Czerew almost 2 years

    I'm attempting a scrollTo() on a webpage and I want a button to trigger the scrollTo(); it will scroll to the top of the form and highlight the first input field.

    My current code works, however the screen quickly flashes. I attempted to use a preventDefault() to no avail. Please see my code below.

    $(document).ready(function () {
        $("#get-started").click(function (e) {
            e.preventDefault();
            $('html, body').animate({
                scrollTop: $("#get-risk").offset().top
            }, 2000);
            $("#get-started-apply-now-form [name='last_name']").focus();
        });
    });
    
  • Jared Michael Czerew
    Jared Michael Czerew over 10 years
    thanks adeneo! by placing the focus in the animations callback it works great!