Can someone please help me convert this jQuery code to plain JS? This is when you scroll down a page, the navigation menu will be fixed.
$(document).ready(function() {
var mainMenu = $('.primaryNav').offset();
$window = $(window);
$window.scroll(function() {
if ($window.scrollTop() >= mainMenu.top) {
$(".primaryNav").addClass("affix");
}
else {
$(".primaryNav").removeClass("affix");
}
});
});
Here we go
const nav = document.querySelector('.primaryNav');
const mainMenuTop = nav.getBoundingClientRect().top;
window.addEventListener('scroll', function(e) {
if (window.pageYOffset >= mainMenuTop) {
nav.classList.add('affix');
} else {
nav.classList.remove('affix');
}
});