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 bo
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>
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";
}