Use jquery to scroll to a specific section on your page from a link or a button.

This little feature can be very handy if you want to auto scroll the page to a particular section. I have used this previously on sites where I want the user to be shown error messages that are on top of a large form. So instead of the user clicking submit and nothing happening the user would click submit and if there were any errors the page would scroll to the error messages on the top of the form.

To achieve this effect create a javascript function like this:
(Thanks to David King from OneDayLater.com for the Opera fix for the button click event!)

function goToByScroll(element) {
    var el = $.browser.opera ? $("html") : $("html, body");
    el.animate({ scrollTop: $(element).offset().top }, 'slow');
}

Now call the above function whenever you want the screen to move to a point. For our example we will scroll on a button click or from a link click using the code below:

$(document).ready(function () {
        //scroll if link click to section2
        $('#Section1 a').click(function (evt) {
            evt.preventDefault();
            goToByScroll('#Section2');
        });
        
        //scroll if button click to section 1 
        $('#SubmitForm').click(function (evt) {
            evt.preventDefault();
            goToByScroll('#Section1');
        });
});

You can view a working demo of this in action here. Simply Right Click and View Source to see the code.


Share this post


blog comments powered by Disqus

Updates

Follow me online at TwitterFacebook or Flickr. If you want to get in touch with me try emailing me.

Latest Tweets