Skip to content

Instantly share code, notes, and snippets.

@morgyface
Created April 13, 2025 20:21
Show Gist options
  • Save morgyface/009845c771ecfb9efd4895209719ef29 to your computer and use it in GitHub Desktop.
Save morgyface/009845c771ecfb9efd4895209719ef29 to your computer and use it in GitHub Desktop.
JS | Change class when scrolling reaches a div
$(function() {
var header = $(".header");
$(window).scroll(function() {
var scroll = $(window).scrollTop();
var position = header.offset().top;
if (scroll >= position) {
header.removeClass('sticky').addClass("static");
} else {
header.removeClass("static").addClass('sticky');
}
});
});
<body>
<div class="content"></div>
<div class="header sticky">
<div class="nav">links</div>
</div>
<div class="content"></div>
</body>
.content {
height: 120vh;
background: blue;
}
.header {
background: green;
height: 2em;
}
.nav {
color: white;
}
.sticky .nav {
position: fixed;
top: 1em;
left: 1em;
}
.static .nav {
position: static;
}
@morgyface
Copy link
Author

Change class when scrolling reaches a div

Having not done much coding lately this took me a while to fathom and I struggled to find anything that fit my requirements.

A few things came close but they were either too convoluted, verbose or used a pixel value. I wanted to essentially do the following:

I want the navigation to be sticky, that is have a fixed position, until the user reaches a div when scrolling down the page, once the div in question is passed, the class is changed, making the navigation static again.

This worked well and there's also a fiddle here.

JavaScript isn't my strongest skill so I'd welcome any advice or pointers on how to improve this, as it's been cobbled together with various snippets. Having said that, it's fairly concise and is working perfectly well.

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