Roshi
Roshi

Reputation: 396

no repeat in javascript

Hello i am new in javascript so sorry for the elementary question, so i want to make the same action to many button it is easy i want to make buttons actives when i click on it so there is my code:

var button = document.querySelector(".button_cadre_work");
	
			button.addEventListener("click", function(e) {
			   this.classList.toggle("is-active"); 
		});
		
		var button = document.querySelector(".over_btn");
	
			button.addEventListener("click", function(e) {
			   this.classList.toggle("is-active"); 
		});
		
		var button = document.querySelector(".button_cadre_about");
	
			button.addEventListener("click", function(e) {
			   this.classList.toggle("is-active"); 
		});

How can i optimize it for don t repeat evrytime

Upvotes: 0

Views: 103

Answers (3)

colecmc
colecmc

Reputation: 3318

You could put the same class on all your elements and the loop through them. I'm using a while loop instead of the array forEach loop.

function loops(items, fn, onLoopComplete) {
  var i;
  try {
    if (items && items.length) {
      i = items.length;
    } else {
      throw new Error(items + ' is required to have a length');
    }

    if (i > -1) {
      do {
        if (items[i] !== undefined) {
          fn(i);
          /* console.log(i + ' is the current iteration'); */
        }
      }
      while (--i >= 0);
    }
    if (typeof onLoopComplete === 'function') {
      onLoopComplete(items.length);
    }
  } catch (e) {
    throw new Error(e);
  }
}

var button = document.querySelectorAll(".buttons");

loops(button, function(i) {
  button[i].addEventListener("click", function(e) {
    alert(button[i].className);
    button[i].classList.toggle("is-active");
  });
});
<li class="buttons button_cadre_work">one</li>
<li class="buttons over_btn">two</li>
<li class="buttons button_cadre_about">three</li>

Upvotes: 1

kaz
kaz

Reputation: 1190

var buttonClickHandler = function(e) {
  this.classList.toggle("is-active"); 
};
NodeList.prototype.forEach = Array.prototype.forEach; //this will allow you to do this in other similar situations
var buttons = document.querySelectorAll('.button_cadre_work, .over_btn, .button_cadre_about').forEach(function(el) {
  el.addEventListener('click', buttonClickHandler);
})

Upvotes: 1

Amadan
Amadan

Reputation: 198324

var buttons = document.querySelectorAll('.button_cadre_work, .over_btn, .button_cadre_about');
var buttonClickHandler = function(e) {
  this.classList.toggle("is-active"); 
};
// EITHER
Array.prototype.forEach.call(buttons, function(button) {
  button.addEventListener('click', buttonClickHandler);
});
// OR
for (var i = 0; i < buttons.length; i++) {
  var button = buttons[i];
  button.addEventListener('click', buttonClickHandler);
}

Upvotes: 1

Related Questions