Skip to content

Instantly share code, notes, and snippets.

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 DevShahidul/a2f81728d8125cebabc3e6ea16e547d2 to your computer and use it in GitHub Desktop.
Save DevShahidul/a2f81728d8125cebabc3e6ea16e547d2 to your computer and use it in GitHub Desktop.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, minimum-scale=1.0, maximum-scale=1.0, initial-scale=1.0, user-scalable=no">
<meta name="format-detection" content="telephone=no">
<title>Endy | Home</title>
<link href="images/favicon.ico" rel="shortcut icon">
</head>
<body>
<header data-scroll-group="header-group">
Header
</header>
<section data-header-group="blue">
Scroll Down (header will become blue)
</section>
<section data-header-group="shadow">
Scroll Down (header will have a shadow, no longer blue)
</section>
<section data-header-group="blue shadow">
Scroll Down (header will have a shadow and be blue)
</section>
<section>
Scroll Down (header will reset)
</section>
<script type="text/javascript">
// This is a handy wrapper function that will return an array of matching element instead of a nodeList
function querySelectorArray(query, root){
return Array.prototype.slice.call((root || document).querySelectorAll(query));
}
// Get all headers that are designated 'scroll-group'
var headers = querySelectorArray('[data-scroll-group]');
// Loop through the headers
headers.forEach(function(header){
// Get the name of the group from the headers [data-scroll-group] attribute
var group = header.getAttribute('data-scroll-group');
// Get all the sections with a matching data-[data-scroll-group] attribute
var sections = querySelectorArray('[data-' + group + ']');
// Create an Event Listener for scrolling
window.addEventListener('scroll', function(){
// Declare a lastSection variable that can store the last class that scrolled by
var lastSection = false;
sections.forEach(function(section){
// Get the elements position compared to the viewport
var offset = section.getBoundingClientRect();
// If the position is smaller than 0 it has scrolled further than that section
// The same is true for the scroll being smaller than the negative height - if so, it is out of view.
if(offset.top < 0 && offset.top > -offset.height) lastSection = section.getAttribute('data-' + group + '');
});
// Apply the class to your header
header.className = lastSection || '';
})
});
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment