I have a website and i want to execute the same action when two buttons are clicked. I tried creating one single function that would be called by each button by using .addEventListener ("click",function())
But i wonder is there a way to know which button called it? for example if i wanted to add a condition inside the function that takes a decision depending on which element called it?
CodePudding user response:
when you pass the function, it receives an event. That event holds a PointerEvent, so that type is an object with many properties of the element, one of them is target
, and the target can get the id of each element like so:
<body>
<button id="b1">
button1
</button>
<button id="b2">
button2
</button>
</body>
<script>
const button1 = document.getElementById('b1')
const button2 = document.getElementById('b2')
const myCustomListener = function(e) {
console.log(e.target.id) // b1 or b2
}
button1.addEventListener('click', myCustomListener )
button2.addEventListener('click', myCustomListener )
</script>
You can also add event listeners dynamically to the buttons like so:
<body>
<button id="b1" >
button1
</button>
<button id="b2" >
button2
</button>
</body>
<script>
const buttons = document.getElementsByClassName('button')
const myCustomListener = function(e) {
console.log(e.target.id) // b1 or b2
}
for (let button of buttons) {
button.addEventListener('click', myCustomListener)
}
</script>
CodePudding user response:
id
s are useful for this (as Juliano points out). Alternatively you could add a descriptive data attribute to each button to identify it (here I've used type
). In the handler you can destructure the type
from the button's dataset, and then do x depending on its value.
// Get the buttons
const buttons = document.querySelectorAll('button');
// Add listeners to them
buttons.forEach(button => {
button.addEventListener('click', handleClick);
});
function handleClick(e) {
// Destructure the type from the button dataset
const { type } = e.target.dataset;
if (type === 'fruit') console.log('Banana');
if (type === 'vegetable') console.log('Potato');
}
<section >
<button data-type="fruit">Surprise fruit!</button>
<button data-type="vegetable">Surprise vegetable!</button>
</section>