Feed on
Posts
Comments

Sometime I’ll see an effect on a website and think nothing of it until I see it implemented on a few other sites in a similar way. Apparently my brain notices these things but it just doesn’t care the first time. It takes it a few viewings for it to wake up and actually take action. This was the case recently when I visited Slashdot. When you scroll down a comments page, a comments control bar will scroll up with the rest of the content until it hits the top of the page. When it does, instead of disappearing up off the top of the page with the rest of the content, it sticks to the top of the viewport while the rest of the page scrolls under it. I realized that I had also seen this effect on Google code and Stackoverflow, albeit in slightly different ways. There are potentially unlimited uses for this effect so I threw some jQuery code (not a plugin) together for this. Why not a plugin? Because it’s essentially two lines of code.

var stickerTop = parseInt($('#sticker').offset().top);
$(window).scroll(function()
{
    $("#sticker").css((parseInt($(window).scrollTop())+parseInt($("#sticker").css('margin-top')) > stickerTop) ? {position:'fixed',top:'0px'} : {position:'relative'});
});

This snippet of code assumes that the block you want to make stick to the top of the browser window has the ID of “sticker”, but you can change it to whatever you like (and it doesn’t need to be a div). You could also expand the condition that checks the position of the window and the “stuck” element and apply a variety of other effects as well.

Here are a couple of basic demos. The first is just a bare bones example and the other uses a template from styleshout and applies the effect to the sidebar on the left. In my tests it works great in Chrome, Firefox, Opera, and IE.

Leave a Reply

You can use these tags: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>