lundi 17 décembre 2018

Adding a single class on multiple elements in if/else statement

I have a script which adds or removes a class to multiple div depending on a scroll position. This works fine as is.

window.addEventListener('scroll', function () {
var sp = window.pageYOffset || document.documentElement.scrollTop;
var logo = document.querySelector(".logo");
var btn = document.querySelector(".toggle-label");

if (sp > 100) {

         logo.classList.add("fade-out");
         btn.classList.add("fade-out");
    }
    else  {
         logo.classList.remove("fade-out");
         btn.classList.remove("fade-out");
    }

});

But I've recently ran across another script which achieves the same in a more eloquent/modern way. (use of let, const & arrow function.)

And I am just trying to learn how I can add/remove a class on multiple div in this modern script.

let scrollpos = window.scrollY
const logo = document.querySelector(".logo")
const logo_height = 400

const add_class_on_scroll = () => logo.classList.add("fade-out")
const remove_class_on_scroll = () => logo.classList.remove("fade-out")


window.addEventListener('scroll', function() { 
  scrollpos = window.scrollY;

  if (scrollpos >= logo_height) { 
      add_class_on_scroll() 
    }
  else { 
      remove_class_on_scroll() }
})

I've began by trying to use array like this.

var fade = [logo, toggle-label];


fade.forEach(function(el) {
  el.classList.add("fade-out")
})

But I am stuck on how to incorporate this array into the if/else statement. I just can't wrap my head around it.

I am not stuck on using array by the way. I am just trying to learn how this can be done in any sensible way.

Any help would be greatly appreciated it.

Aucun commentaire:

Enregistrer un commentaire