Skip to content

Instantly share code, notes, and snippets.

@VinnyFonseca
Last active January 12, 2023 16:08
Show Gist options
  • Star 12 You must be signed in to star a gist
  • Fork 3 You must be signed in to fork a gist
  • Save VinnyFonseca/6c1692c9ce3704b1a48ad401c22602e5 to your computer and use it in GitHub Desktop.
Save VinnyFonseca/6c1692c9ce3704b1a48ad401c22602e5 to your computer and use it in GitHub Desktop.
addEventListener multiple events
['change', 'keyup', 'paste', 'input', 'propertychange', 'every_other_event_you_want'].forEach(eventType => {
[...document.querySelectorAll('SELECTOR')].forEach(element => {
element.addEventListener(eventType, (event) => {
console.log(event);
// Your callback here
}, false);
});
});
@cgahmann
Copy link

cgahmann commented Dec 2, 2022

Thanks for the script, however it gets an error. Here is the correct version.

['blur', 'keyup', 'change', 'click'].forEach((event) => {
    modal.querySelectorAll('form input').forEach((formInput) => {
        formInput.addEventListener(event, () => {
            // Your callback here
        });
    });
});

@VinnyFonseca
Copy link
Author

VinnyFonseca commented Dec 3, 2022

You're right, as I'm using querySelectorAll there should be a forEach after it. Don't forget to Array spread the element query. Amended.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment