🔰register handler
Last updated
Last updated
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()
let button = document.querySelector("#mybutton");
// ⭐ registering with `addEventListener()`
button.addEventListener("click", () => {
console.log("Thanks again!");
});
// ⭐ registering a "capturing" event handler
document.addEventListener("click", handleClick, true);
// ⭐ explicitly specifies the options
document.addEventListener("click", handleClick, {
capture: true, // ⭐ capturing handler
once : true, // ⭐ automatically removed after triggered once
passive: true // ⭐ can't cancel default actions
});
registering handlers on event target's "on" properties (onclick, onchange, ...):
缺點:
針對特定的 event target + event type (如:windown.onload),一次只能設定一個 event handler。
如果前面已經有設定一個 event handler,後面設定的 event handler 會蓋掉前面的。
// ⭐ registering `window.onload`
// invoked when `document` is loaded
window.onload = function() {
// Look up a <form> element
let form = document.querySelector("form#shipping");
// ⭐ registering `form.onsubmit`
// invoked before the form is submitted.
form.onsubmit = function(event) {
// assume: `isFormValid()` defined elsewhere.
// if inputs not valid, prevent form submission.
if (!isFormValid(this)) event.preventDefault();
};
};