jQuery Stick ’em: Make Content Sticky on Scroll, to a Point
Trevor Davis, Former Front-End Development Technical Director
Article Categories:
Posted on
Over time, we've been adding some additional pieces of flair to the Viget site. The most recent addition was on the invidual work pages. We have large process sections where we illustrate a part of a project's process with several images and a block of text. The problem: some of those images were very tall. So by the time you scrolled down to the bottom of the images, you would have to scroll back up just to read the text to give you context about the images you had just viewed. The solution: make the content sticky as you are scrolling. The block of text I am referring to is outlined in orange in the following image.
The tricky part was that I couldn’t just make the text position: fixed once it reached the top of the screen and be done with it. Since there are many of these process sections on a page, I had to "un-stick" the content at a point too. So I came up with a plugin, jQuery Stick ‘em, to enable this functionality.
The Code
Here is some sample markup:
<div class="container"> <div class="row stickem-container"> <div class="content"> Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.… </div> <div class="aside stickem"> I'm gonna be sticky! </div> </div> </div>
The content that I want to "stick" is div.stickem, and I want it to be "sticky" within div.stickem-container. Since I am using the plugin's default class names, I can just call it like this:
$('.container').stickem();
Plugin Options & Defaults
- item: '.stickem'
Items that you want to stick on scroll. - container: '.stickem-container'
Parent container that you want the sticky item to be contained in. - stickClass: 'stickit'
Class added to the sticky item once it should start being sticky. - endStickClass: 'stickit-end'
Class added to the sticky item once it has reached the end of the container - offset: 0
Do you already have a fixed horizontal header on the page? Offset stick 'em by that many pixels. - start: 0
If your sticky item isn't at the top of the container, tell it where it should start being sticky.
Since the plugin is just adding classes to the items, you will need to setup your CSS with something like this:
.stickem-container { position: relative; } .stickit { margin-left: 660px; position: fixed; top: 0; } .stickit-end { bottom: 0; position: absolute; right: 0; }
But, it's really flexible, so you can do whatever you want with those classes. So go download the plugin on GitHub and check out the demo.