javascript - Pure js add and remove (toggle) class after scrolling x amount? -
i don't want use jquery this.
it's simple, want add class after scrolling past amount of pixels (lets 10px) , remove if ever go top 10 pixels.
my best attempt was:
var scrollpos = window.pageyoffset; var header = document.getelementbyid("header"); function add_class_on_scroll() { header.classlist.add("fade-in"); } function remove_class_on_scroll() { header.classlist.remove("fade-in"); } window.addeventlistener('scroll', function(){ if(scrollpos > 10){ add_class_on_scroll(); } else { remove_class_on_scroll(); } console.log(scrollpos); });
but console shows number continues grow regardless of scrolling or down. , class fade-in
never gets added, though console shows past 10.
you forgot change offset value in scroll handler.
//use window.scrolly var scrollpos = window.scrolly; var header = document.getelementbyid("header"); function add_class_on_scroll() { header.classlist.add("fade-in"); } function remove_class_on_scroll() { header.classlist.remove("fade-in"); } window.addeventlistener('scroll', function(){ //here forgot update value scrollpos = window.scrolly; if(scrollpos > 10){ add_class_on_scroll(); } else { remove_class_on_scroll(); } console.log(scrollpos); });
now code works properly
explanation
there no documentation that, asked for. issue in logic workflow.
when scrollpos = window.scrolly
page @ top-offset of 0, variable stores value. when page scrolls, scroll
listener fires. when yout listener checks scrollpos
value, value still 0
, of course. if, @ every scroll handler, update scrollpos
value, can have dynamic value.
another option create getter, like
var scrollpos = function(){return window.scrolly};
this way can dynamically check method return @ every offset.
if(scrollpos() > 10)
see? hope helped. (:
Comments
Post a Comment