javascript - In vanilla JS, how can I add or remove a class from an element based on whether the scroll is at the top? -
i'm trying make sticky nav have particular class when not scrolled @ top, , not have class when scrolled @ top. sorry if that's confusing.
what i'm stuck on right fact in bottom piece of code doc.scrolltop == 0
evaluating true
whenever scroll mouse. doing wrong?
htmlelement.prototype.removeclass = function(remove) { var newclassname = ""; var i; var classes = this.classname.split(" "); for(i = 0; < classes.length; i++) { if(classes[i] !== remove) { newclassname += classes[i] + " "; } } this.classname = newclassname; } window.onscroll = function() { var body = document.body; //ie 'quirks' var doc = document.documentelement; //ie doctype doc = (doc.clientheight) ? doc : body; if ( doc.scrolltop == 0 ) { document.getelementbyid('top').removeclass('scrolling'); console.log("doc.scrolltop == 0");//test } else { document.getelementbyid('top').addclass('scrolling'); // need make addclass function ... console.log("doc.scrolltop != 0");//test } };
try using distance top:
var distance = (window.pageyoffset || doc.scrolltop) - (doc.clienttop || 0);
and in code:
htmlelement.prototype.removeclass = function(remove) { var newclassname = ""; var i; var classes = this.classname.split(" "); for(i = 0; < classes.length; i++) { if(classes[i] !== remove) { newclassname += classes[i] + " "; } } this.classname = newclassname; } window.onscroll = function() { var body = document.body; //ie 'quirks' var doc = document.documentelement; //ie doctype doc = (doc.clientheight) ? doc : body; var distance = (window.pageyoffset || doc.scrolltop) - (doc.clienttop || 0); if ( distance === 0 ) { document.getelementbyid('top').removeclass('scrolling'); console.log("doc.scrolltop == 0");//test } else { document.getelementbyid('top').addclass('scrolling'); // need make addclass function ... console.log("doc.scrolltop != 0");//test } };
whilst works, suggest looking @ improving js code in line more modern practices.
Comments
Post a Comment