javascript dynamic element onclick code example
Example 1: document on click dynamic element
$(document).on('click', '.class', function() {
});
Example 2: javascript bind event to created element
document.addEventListener('click', function(e){
if(e.target && e.target.id== 'myDynamicallyAddedElementID'){
}
});
$(document).on('click','#myDynamicallyAddedElementID',function(){
});
Example 3: 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)