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.

Tags: ,

Comments

2/25/2010 12:39:42 AM #

David King

Breaks in Opera Wink

// Sloppy fix for opera
var el = $.browser.opera ? $("html") : $("html, body");
el.animate (...

David King |

2/25/2010 10:41:27 AM #

richard reddy

Thanks Dave, nice find!

I've updated the demo and works great now in Opera. I only have Opera on my work PC so didn't get a chance to check it at home. I have tested in IE8, FF3.6, Chrome and Safari and all worked...but typical, it was broken in the one I couldn't test! haha

I think the morale of this tale is to download Opera at home! Smile

Cheers,
Rich

richard reddy |

2/25/2010 7:43:14 PM #

David King

No worries, I kinda wish I knew *why* Opera flickers like that and then you could test for the object rather than the browser. Sods law always applies!

I've added the script to 1DayLater too, 'cept I've named it ninjaScroll Smile

David King |

Comments are closed