🔰register handler
JS ⟩ browser ⟩ event ⟩ handler ⟩ register
register an event (function) handler:
// 1. by setting the "on" property
window.onload = function(){ ... };
// 2. by calling addEventListener()
elem.addEventListener("click", handler, opts);register an event object handler:
elem.addEventListener('click', {
handleEvent(event) { ... } // ⭐️ required method
});Don’t use setAttribute to assign handlers. Attributes are always strings, function becomes a string❗
// a click on will generate errors.
elem.setAttribute('onclick', () => { ... });For some events, handlers only work with addEventListener.
document.onDOMContentLoaded = handler; // ❌ won't work❗️
document.addEventListener("DOMContentLoaded", handler) // ✅ The third argument to addEventListener() is a boolean value or object. If you pass true, then the handler is registered as a capturing 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.
});Don’t use setAttribute() to register handlers, it won’t work:
// ⭐️ attributes are ALWAYS strings❗️
// function will be converted to a string automatically.
document.body.setAttribute('onclick', function() { alert(1) });registering a
object handler - event handler can be an object. ⭐️
registering with addEventListener()
registering handlers on event target's "on" properties (onclick, onchange, ...):
缺點:
針對特定的 event target + event type (如:windown.onload),一次只能設定一個 event handler。
如果前面已經有設定一個 event handler,後面設定的 event handler 會蓋掉前面的。
Last updated
Was this helpful?