๐ฐ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()
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();
};
};Last updated
Was this helpful?