Im trying to rewrite a jquery script i like in vanilla javascript and its not going well here is the original: jquery:
$(window).scroll(function(){
if ($(window).scrollTop() >= 225) {
$('.sticky-nav').addClass('fixed-header');
$('.site-title').addClass('visible-title');
}
else {
$('.sticky-nav').removeClass('fixed-header');
$('.site-title').removeClass('visible-title');
}
});
so far ive changed it to:
window.onscroll = function() {
if (document.window.scrollTop == 225 || document.documentElement.scrollTop == 225) {
$('.sticky-nav').addClass('fixed-header');
$('.site-title').addClass('visible-title');
}
else {
$('.sticky-nav').removeClass('fixed-header');
$('.site-title').removeClass('visible-title');
}
}
codepen:https://codepen.io/robot_head/pen/WKverK
I dont get what to do for the if statement, or how to rewrite the add and remove class lines. Some pointers here would be helpful
You can use
document.querySelector('.sticky-nav').classList.add()
and
document.querySelector('.sticky-nav').classList.remove()
in case you know it is only one element that matches (or if the first match is the one you want).
Otherwise use
document.querySelectorAll
instead, but be aware that the result is aNodeList
(even if it finds only one element), which you must iterate manually, e.g.