Skip to content

Instantly share code, notes, and snippets.

@mundry
Last active December 30, 2015 13:19
Show Gist options
  • Save mundry/7834871 to your computer and use it in GitHub Desktop.
Save mundry/7834871 to your computer and use it in GitHub Desktop.
Sticky sidebar following the user as they scroll.
<!DOCTYPE html>
<html class="no-js">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<title>Sticky Sidebar</title>
<meta name="description" content="">
<meta name="viewport" content="width=device-width, initial-scale=1">
<!-- Place favicon.ico and apple-touch-icon(s) in the root directory -->
<style>
body {
width: 960px;
margin: 0 auto;
}
aside {
margin-top: 0;
width: 25%;
float: right;
background-color: #FFAA00;
border-radius: 10px;
}
aside ul {
padding: 15px;
list-style: none;
}
aside ul li {
padding: 15px 0;
}
aside ul li a {
text-decoration: none;
color: #333;
}
#content {
width: 75%;
float: left;
}
#content p {
padding-right: 15px;
text-align: justify;
}
</style>
</head>
<!--[if lt IE 7]> <body class="lt-ie9 lt-ie8 lt-ie7"> <![endif]-->
<!--[if IE 7]> <body class="lt-ie9 lt-ie8"> <![endif]-->
<!--[if IE 8]> <body class="lt-ie9"> <![endif]-->
<!--[if gt IE 8]><!--> <body> <!--<![endif]-->
<aside>
<ul>
<li><a href="#">Point 1</a></li>
<li><a href="#">Point 2</a></li>
<li><a href="#">Point 3</a></li>
<li><a href="#">Point 4</a></li>
<li><a href="#">Point 5</a></li>
</ul>
</aside>
<div id="content"></div>
<script>
var p = '<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Quia, commodi, aspernatur doloribus doloremque laborum cumque expedita labore numquam voluptates ad officia quo natus nisi sed vitae. Doloremque, fugit illum facilis. Lorem ipsum dolor sit amet, consectetur adipisicing elit. Voluptates, doloribus, illo, porro tenetur aut eius quam dolore neque tempore quidem modi eum dolores aperiam magnam placeat consectetur quaerat explicabo iure.</p>';
var content = document.getElementById('content');
for (var i = 0; i < 30; i++) {
content.innerHTML += p;
}
</script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script src="sticky-sidebar.js"></script>
</body>
</html>
$(function() {
var $sidebar = $("aside"),
$window = $(window),
offset = $sidebar.offset(),
topPadding = 15;
$window.scroll(function() {
if ($window.scrollTop() > offset.top) {
$sidebar.css('margin-top', $window.scrollTop() - offset.top + topPadding);
// $sidebar.stop().animate({ marginTop: ($window.scrollTop() - offset.top + topPadding) });
} else {
$sidebar.removeAttr('style');
// $sidebar.stop().animate({ marginTop: 0 });
}
});
})();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment