🔰register handler
// 1. by setting the "on" property
window.onload = function(){ ... };
// 2. by calling addEventListener()
elem.addEventListener("click", handler, opts);elem.addEventListener('click', {
handleEvent(event) { ... } // ⭐️ required method
});// a click on will generate errors.
elem.setAttribute('onclick', () => { ... });document.onDOMContentLoaded = handler; // ❌ won't work❗️
document.addEventListener("DOMContentLoaded", handler) // ✅ elem.addEventListener("click", handler, {
capture: true, // ⭐️ registered as a "capturing" handler.
once : true, // ⭐️ automatically removed after triggered once.
passive: true // ⭐️ can't cancel default actions.
});// ⭐️ attributes are ALWAYS strings❗️
// function will be converted to a string automatically.
document.body.setAttribute('onclick', function() { alert(1) });Last updated