Back to all Digital Media resources examples
Scroll Then Stick to Top
Scroll to see the example

The green bars and the photo below start offset from the top of the screen. When user scrolls, the elements scroll with the page and then STICKS to the top of the page. This technique can be used for any element

  • Placed on the left
  • Placed in the middle - note that photo (or any element) can "get stuck" at any vertical position
  • Place on the right
Here's the HTML Code

<div id="topHeader">Header at top of page</div>
<div id="elementLeft">Element on the left content</div>
<div id="elementMiddle">Element in the middle content</div>
<div id="elementRight">Element on the right content</div>
Here's CSS Code

#topHeader {
width: 100%;
height: auto;
text-align: center;
position: fixed;
top: 0px;
left: 0px;
}
#elementRight {
position: absolute;
top: 100px;
right: 0;
}
#elementMiddle{
width:640px;
height:auto;
margin:0 auto;
position:relative;
top:0;
}
#elementLeft {
position: absolute;
top: 200px;
left: 0;
}
Here's the jQuery Code

You'll need these scripts in the <head> of your html page


<script src="http://www.freestyleacademy.rocks/jquery/minified.js"></script>

Here's the script that make the whole thing function properly


$(window).bind('scroll',function(e){
stickToTop();
});
var elementRightY = parseInt($("elementRight").offset().top), scrollRatio = 0.8;
var elementMiddleY = parseInt($("#elementMiddle").offset().top);
var elementMiddleX = parseInt($("#elementMiddle").offset().left);
var elementLeftY = parseInt($("#elementLeft").offset().top);
function stickToTop(){
var scrolled = parseInt($(window).scrollTop());
if(scrolled >= elementRightY*scrollRatio){
$("elementRight").css({
"position":"fixed",
"top":"0"
});
}
if(0 <= scrolled && scrolled < elementRightY*scrollRatio) {
$("elementRight").css({
"position":"absolute",
"top":elementRightY-scrolled/4
});
}
if(scrolled >= (elementMiddleY+$("#topHeader").outerHeight())*scrollRatio){
$("#elementMiddle").css({
"position":"fixed",
"top":$("#topHeader").outerHeight(),
"left":elementMiddleX
});
}
if(0 <= scrolled && scrolled < elementMiddleY*scrollRatio) {
$("#elementMiddle").css({
"position":"relative",
"left":"0"
});
}
if(scrolled >= elementLeftY*scrollRatio){
$("#elementLeft").css({
"position":"fixed",
"top":"0"
});
}
if(0 <= scrolled && scrolled < elementLeftY*scrollRatio) {
$("#elementLeft").css({
"position":"absolute",
"top":elementLeftY-scrolled/4
});
}
}