Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jquery scroll to form input

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();
    });
});
like image 364
Jared Michael Czerew Avatar asked Feb 17 '26 04:02

Jared Michael Czerew


1 Answers

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();
        });
    });
});
like image 198
adeneo Avatar answered Feb 20 '26 20:02

adeneo



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!