Scrolling fun and games with jQuery

Parallax scrolling has been popular for some years now. Watch the nearer clouds scroll faster than the ones in the distance! But the technique has its uses.

Fixed navigation

Several sites respond to scrolling actions in creative and useful ways. For example, ABCNews removes the full navigation bar after the user scrolls it out of view, replacing it with a more compact version.

I've used the same fixed-but-responsive navigation pattern on this site. While developing it, I discovered that responding to the scroll event is sufficiently complicated to warrant a third-party library. I settled on skrollr, which works reasonably well.

Taking it further

Having gotten up to speed on the scroll event, I then wondered about other scrolling-related events that might be worth paying attention to. How about an easy way to detect if scroll bars are present? It would be nice to compensate for the slight leftward jog triggered by going from a non-scrolling page to a scrolling one. And how about detecting if the page is scrolled? That would be useful for making a "back to top" link appear. Rather than dealing with skrollr and its ilk, I wanted to find the simplest possible way to respond to the presence of these conditions.

JavaScript, of course, can easily detect both of these, either directly or indirectly. From there, it’s a short step to writing a Modernizr-style function. Start by assuming that the page isn’t scrolled in either direction, and doesn’t have scrollbars in either direction, and insert the appropriate classes on the <html> tag: no-scroll, no-vertical-scroll, no-horizontal-scroll, not-scrolled, etc. Run the various tests, and remove and replace the appropriate classes: vertical-scroll replaces no-vertical-scroll, and so on.

The minified version is only 953B (see Downloads, below), so you should just paste it into your main JavaScript file. Assuming you've already called jQuery, you simply call it as follows:

$('html').add_scroll_classes();

Note that you should call this function not only on $(document).ready(), but also on $(document).resize() and on $(window).scroll(). Use it in your CSS per this simplified example:

.not-scrolled-vertically .widget {
    display: none;
}
.scrolled-vertically .widget {
    display: block;
}

Downloads

Download the example code.

Posted in:

comments powered by Disqus