Answers for "javascript click event dynamic content"

4

document on click dynamic element

$(document).on('click', '.class', function() {
    // do something
});
Posted by: Guest on September-19-2020
0

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)
Posted by: Guest on April-15-2021

Code answers related to "javascript click event dynamic content"

Code answers related to "Javascript"

Browse Popular Code Answers by Language