Created
April 13, 2025 20:21
-
-
Save morgyface/009845c771ecfb9efd4895209719ef29 to your computer and use it in GitHub Desktop.
JS | Change class when scrolling reaches a div
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
$(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'); | |
} | |
}); | |
}); |
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
<body> | |
<div class="content"></div> | |
<div class="header sticky"> | |
<div class="nav">links</div> | |
</div> | |
<div class="content"></div> | |
</body> |
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
.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; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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:
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.