Skip to content

Instantly share code, notes, and snippets.

@JoeSz
Created September 24, 2016 15:48
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save JoeSz/48743c0d898bf6e6735064cc3d564a9d to your computer and use it in GitHub Desktop.
Save JoeSz/48743c0d898bf6e6735064cc3d564a9d to your computer and use it in GitHub Desktop.
Detect element is in the viewport and then change browser url
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Scrolling URL Hash</title>
<meta name="description" content="Webpage for xxxx">
<style>
body {
height: 2000px;
}
a > div {
min-height: 500px;
}
</style>
</head>
<body>
<a href="#anchor1" id="anchor1" class="anchor"><div>ANCHOR 1</div></a>
<a href="#anchor2" id="anchor2" class="anchor"><div>ANCHOR 2</div></a>
<a href="#anchor3" id="anchor3" class="anchor"><div>ANCHOR 3</div></a>
<a href="#anchor4" id="anchor4" class="anchor"><div>ANCHOR 4</div></a>
<a href="#anchor5" id="anchor5" class="anchor"><div>ANCHOR 5</div></a>
<a href="#anchor6" id="anchor6" class="anchor"><div>ANCHOR 6</div></a>
<script src="http://code.jquery.com/jquery-2.1.4.min.js"></script>
<script>
// Source: http://stackoverflow.com/questions/30734552/change-url-while-scrolling
// stackoverflow.com/questions/123999/how-to-tell-if-a-dom-element-is-visible-in-the-current-viewport
function isElementInViewport (el) {
//special bonus for those using jQuery
if (typeof jQuery === "function" && el instanceof jQuery) {
el = el[0];
}
var rect = el.getBoundingClientRect();
return (
rect.top >= 0 &&
rect.left >= 0 &&
rect.bottom <= (window.innerHeight || document.documentElement.clientHeight) && /*or $(window).height() */
rect.right <= (window.innerWidth || document.documentElement.clientWidth) /*or $(window).width() */
);
}
// click-to-scroll behavior
$(".anchor").click(function (e) {
e.preventDefault();
var section = this.href;
var sectionClean = section.substring(section.indexOf("#"));
$("html, body").animate({
scrollTop: $(sectionClean).offset().top
}, 1000, function () {
window.location.hash = sectionClean;
});
});
// listen for the scroll event
$(document).on("scroll", function() {
console.log("onscroll event fired...");
// check if the anchor elements are visible
$(".anchor").each(function (idx, el) {
if ( isElementInViewport(el) ) {
// update the URL hash
if (window.history.pushState) {
var urlHash = "#" + $(el).attr("id");
window.history.pushState(null, null, urlHash);
}
}
});
});
</script>
</body>
@haleyngonadi
Copy link

Thank you so much!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment