HackYa
HackYa

Reputation: 105

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.

Upvotes: 1

Views: 93

Answers (2)

Pete
Pete

Reputation: 58442

Just substitute them in for the place where you add and remove your classes:

let scrollpos = window.scrollY
var elements = [document.querySelector(".logo"), document.querySelector(".toggle-label")];  // get your elements
const logo_height = 400

const add_class_on_scroll = () => {
  elements.forEach(function(el) {         // loop to add class
    el.classList.add("fade-out");
  });
};
const remove_class_on_scroll = () => {
  elements.forEach(function(el) {         // loop to remove class
    el.classList.remove("fade-out");
  });
};

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

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

Upvotes: 1

flowtron
flowtron

Reputation: 854

Not all browsers support LET and/or ARROW-functions! Your approach with forEach is not quite right.

fade.forEach( function(one_fade_id){
  document.querySelect( '#'+ one_fade_id ).classList.add( "fade-out" )
} )

or

fade.forEach( (fadeId) => { 
  document.querySelect( '#'+ fadeId ).classList.add( "fade-out" ) 
} )

Upvotes: 0

Related Questions