CJ Broersma
CJ Broersma

Reputation: 189

jQuery smooth scroll and align to middle of the page an input after error message

I am making a jQuery function that will alert users if they did not fill out an input on an HTML form. After a custom message I would like the page to scroll the input to the middle. The code below works well, but I was hoping for a smooth slow scroll to get the user's attention. How can I use jQuery animate to achieve this?

function errormessage(msg, div){
    alert(msg);
    var $window = $(window),
        $element = $('#' + div),
        elementTop = $element.offset().top,
        elementHeight = $element.height(),
        viewportHeight = $window.height(),
        scrollIt = elementTop - ((viewportHeight - elementHeight) / 2);

    $window.scrollTop(scrollIt);
}

Upvotes: 1

Views: 48

Answers (1)

Isman F.
Isman F.

Reputation: 759

I couldn't try your code, but I believe that replacing this:

$window.scrollTop(scrollIt);

with this:

$('html, body').animate({
   scrollTop: scrollIt
}, 2000);

should do the trick.

Upvotes: 2

Related Questions