Concise event listeners on array elements

I was wondering if there is a more concise way to perform this same action.

I'm trying to listen for events on two separate buttons that perform the same action, and both buttons have the same class of 'return' and I've assigned them to an array called 'returnButton'. I'd like to have one event listener that can listen on both buttons and pass the button that was clicked onto my returnToMainContent function.

The code in its current state functions properly, but I believe there should be a way to eliminate one of my event listeners. I'm floundering in my attempts to do so.

const returnButton = document.querySelectorAll('.return');
const mainContent = document.querySelector('#main-content');

returnButton[0].addEventListener('click', () => {returnToMainContent(returnButton[0])});
returnButton[1].addEventListener('click', () => {returnToMainContent(returnButton[1])});

function returnToMainContent(button){
    button.parentElement.style.display = "none";
    mainContent.style.display = "block";
}

Help is greatly appreciated!

Answers:

Answer

If you just want to have a single call to addEventListener then you can use event delegation by setting the event listener on a common parent element. For instance you could set it on document. You would then get which button that was clicked from the target property from the event object that is automatically passed to event listeners

document.addEventListener('click',event=>{
  var button = event.target;
  //check that the element click was one of the 'return' buttons
  if(button.classList.contains('return')){
    returnToMainContent(button);
  }
});

function returnToMainContent(button){
    button.parentElement.style.display = "none";
    mainContent.style.display = "block";
}
Answer

I am not sure that one event handler is good. It could be if you are adding 100s of events. If it is a few, that you can easily just use a loop to add them.

const returnButtons = document.querySelectorAll('.return');

function test () {
  console.log(this.textContent) //can use this
}

returnButtons.forEach( function (btn) {
  btn.addEventListener("click", test)
})
<button class="return">One</button>
<button class="return">Two</button>

Tags

Recent Questions

Top Questions

Home Tags Terms of Service Privacy Policy DMCA Contact Us Javascript

©2020 All rights reserved.