Skip to content

Instantly share code, notes, and snippets.

@amboy00
Created March 27, 2013 20:55
Show Gist options
  • Save amboy00/5257921 to your computer and use it in GitHub Desktop.
Save amboy00/5257921 to your computer and use it in GitHub Desktop.
A CodePen by Chris Williams. Sticky Div - Basic example how to make a div stick to the tippy top of a page by scrolling. Uses jQuery
%header
%h1 Say “hello” to my sticky div!
#stickySpace
#sticky
“Hello.”
%p scroll down ↓
%p scroll down ↓
%p scroll down ↓
%p scroll down ↓
%p scroll down ↓
%p scroll down ↓
%p scroll down ↓
%p scroll down ↓
%p scroll down ↓
%p scroll down ↓
%p scroll down ↓
%p scroll down ↓
%p scroll down ↓
%p scroll down ↓
%p scroll down ↓
%p scroll down ↓
%p scroll down ↓
%p scroll down ↓
%p scroll down ↓
%p scroll down ↓
%p scroll down ↓
%p scroll down ↓
%p scroll down ↓
%p scroll down ↓
%p scroll down ↓
%p scroll down ↓
%p scroll down ↓
%p scroll down ↓
%p scroll down ↓
%p scroll down ↓
var scrollPos, stick, stickyDiv, stickyDivOffset, stickyState, unstick;
scrollPos = 0;
stickyDiv = $("#sticky");
stickyDivOffset = stickyDiv.offset();
stickyState = "unstuck";
$(document).on("scroll", function() {
scrollPos = $(this).scrollTop();
if (scrollPos >= stickyDivOffset.top) {
stick();
} else {
unstick();
}
return stickyDiv.text(scrollPos);
});
stick = function() {
if (stickyState === "unstuck") {
stickyDiv.addClass("stick");
return stickyState = "stuck";
}
};
unstick = function() {
if (stickyState === "stuck") {
stickyDiv.removeClass("stick");
return stickyState = "unstuck";
}
};
@import "compass";
body {
font-family: sans-serif;
margin: 0;
text-align: center;
background: #333 url(/images/classy_fabric.png);
color: white;
font-family: "Lucida Grande", "Lucida Sans Unicode", Tahoma, Sans-Serif;
header {
margin: 5em 0;
}
#stickySpace {
height: 120px;
}
#sticky {
position: static;
background: #000000;
height: 60px;
line-height: 60px;
width: 50%;
margin: 0 auto;
&.stick {
position: fixed;
top: 0;
left: 50%;
margin-left: -25%;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment