Skip to content

Instantly share code, notes, and snippets.

@Archie22is
Last active November 2, 2015 08:29
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Archie22is/66e04551e82b87fb297a to your computer and use it in GitHub Desktop.
Save Archie22is/66e04551e82b87fb297a to your computer and use it in GitHub Desktop.
Scroll to page
<div id="fixed">
My fixed bar
</div>
<div id="targets">
<div id="target-1">
<a href="#target-2">Jump to target 2</a>
</div>
<div id="target-2">
<a href="#target-3">Jump to target 3</a>
</div>
<div id="target-3">
<a href="#target-4">Jump to target 4</a>
</div>
<div id="target-4">
<a href="#target-5">Jump to target 5</a>
</div>
<div id="target-5">
<a href="#target-1">Jump to target 1</a>
</div>
</div>
/**
* Check a href for an anchor. If exists, and in document, scroll to it.
* If href argument ommited, assumes context (this) is HTML Element,
* which will be the case when invoked by jQuery after an event
*/
function scroll_if_anchor(href) {
href = typeof(href) == "string" ? href : $(this).attr("href");
// You could easily calculate this dynamically if you prefer
var fromTop = 50;
// If our Href points to a valid, non-empty anchor, and is on the same page (e.g. #foo)
// Legacy jQuery and IE7 may have issues: http://stackoverflow.com/q/1593174
if(href.indexOf("#") == 0) {
var $target = $(href);
// Older browser without pushState might flicker here, as they momentarily
// jump to the wrong position (IE < 10)
if($target.length) {
$('html, body').animate({ scrollTop: $target.offset().top - fromTop });
if(history && "pushState" in history) {
history.pushState({}, document.title, window.location.pathname + href);
return false;
}
}
}
}
// When our page loads, check to see if it contains and anchor
scroll_if_anchor(window.location.hash);
// Intercept all anchor clicks
$("body").on("click", "a", scroll_if_anchor);
body {
padding:0;
margin:50px 0 0;
font-family:"Arial";
font-size:1em;
}
a { color:#333; }
#fixed {
position:fixed;
height:50px;
line-height:50px;
vertical-align:middle;
background:#000;
top:0;
left:0;
right:0;
color:#FFF;
padding-left:5px;
}
#targets div {
height:400px;
padding-left:5px;
}
#target-1 { background:#888; }
#target-2 { background:#999; }
#target-3 { background:#AAA; }
#target-4 { background:#BBB; }
#target-5 { background:#CCC; }
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment