assign onclick event dynamically javascript code example

Example: how to create dynamic onclick event in javascript

/* This example assumes you have two elements with an id 
    attribute of 'cats' and 'dogs'.
*/

const conditionOneHandler = event => {
  alert('I like cats!');
}

const conditionTwoHandler = event => {
  alert('I like dogs!');
}
  
const clickHandler = (event) => {

  // Do whatever. You can use the target object
  // from the event to conditionally handle the
  // event.
  switch (event.target.id) {
    default: return;
    case 'dogs': return conditionOneHandler(event);
    case 'cats': return conditionTwoHandler(event);
    
  }

} 

/* 
	Attach the click event listener to the element.
    You can also use a comma after each line to declare
    multiple variables of the same type, instead of 
    writing 'const' every time. :)
*/

const dogsEl = document.querySelector('#dogs'),
      catsEl = document.querySelector('#cats'),
      dogsEl.onclick = event => clickHandler(event),
      catsEl.onclick = event => clickHandler(event)