I often times easily implemented event delegation with the "click" event on parent elements of something with code like
HTML:
<div>
<span>
<input
type="radio"
id="all0"
name="difficulty-ask"
class="difficultyaskclass"
value="all"
checked="checked"
/>
<label for="all0">All</label>
<input
type="radio"
id="2easy1"
name="difficulty-ask"
class="difficultyaskclass"
value="easy"
/>
<label for="2easy1">Easy</label>
<input
type="radio"
id="2med2"
name="difficulty-ask"
class="difficultyaskclass"
value="medium"
/>
<label for="2med2">Medium</label>
<input
type="radio"
id="2hard3"
name="difficulty-ask"
class="difficultyaskclass"
value="hard"
/>
<label for="2hard3">Hard</label>
</span>
</div>
JS:
parentelement.addEventlistener('click', (event) => {
if(event.target.classList.contains('targetelement'){Code..}};
(parentelement is just a regular div, in which the radio buttons are placed)
How does it work now with the ‘change’ event for example for radio buttons if they switch state?
I made it work first by just looping through all of them and then add an eventListener to each. But this is obviously not the desired solution, i definitely need some event delegation there.
2
Answers
you may use
input
event, which is also valid for any forms elementsdemo:
You can also use click or also change as you have2 choice value. You can use event delegation combined with call() method. here I added event delegation to an added input type checkbox