I have done my research but i cant find anything useful that are related to my question.
Original JavaScript Code
$(\"#furniture1\")
Option 1: Use event delegation. This solution is pure javascript:
document.querySelector('body').addEventListener('keyup', (e) => {
if (e.target.classList.contains('keyup-capturer')) {
somefunction();
}
});
$ctr = document.getElementById('counter');
document.querySelector('body').addEventListener('keyup', (e) => {
if (e.target.classList.contains('keyup-capturer')) {
somefunction();
}
});
function somefunction() {
console.log(`Fired from the input ${this.id}`);
$ctr.innerHTML = parseInt($ctr.innerHTML, 10) + 1;
};
Key Ups: 0
Option 2 [*]: If you do need to use jQuery, you can either use event delegation, or use a class
for calling the same function on when keyup is captured in any element on that class:
$('.keyup-capturer').keyup(function() { samefunction(); });
And assign the .keyup-capturer
class to all the #furniture-x
and #color-x
element IDs.
I don't recommend this approach anymore. See the discussion below.
[*] Some observations:
forEach
or map
to attach event handlers. You'll just be adding a lot of event handlers, and eventually, you'll find your page growing slower with more complexity.$('.c1')
, or attribute selectors $('[disabled]')
, etc), keep in mind this fact. Thanks to @t.niese for pointing this out in the comments.