Created
September 24, 2016 15:48
-
-
Save JoeSz/48743c0d898bf6e6735064cc3d564a9d to your computer and use it in GitHub Desktop.
Detect element is in the viewport and then change browser url
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<!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> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Thank you so much!