how to add onclick event dynamically in javascript code example
Example: how to create dynamic onclick event in javascript
const conditionOneHandler = event => {
alert('I like cats!');
}
const conditionTwoHandler = event => {
alert('I like dogs!');
}
const clickHandler = (event) => {
switch (event.target.id) {
default: return;
case 'dogs': return conditionOneHandler(event);
case 'cats': return conditionTwoHandler(event);
}
}
const dogsEl = document.querySelector('#dogs'),
catsEl = document.querySelector('#cats'),
dogsEl.onclick = event => clickHandler(event),
catsEl.onclick = event => clickHandler(event)