Event handlers
Event Handlers
3 ways to add event handler to an HTML element:
- using the HTML attribute e.g. - onclickor- onmouseover- <button onclick="makePayment()" id="paymentSubmit">Make Payment</button>
- Using DOM in JS - let paymentButton = document.querySelector('#paymentSubmit'); paymentButton.onclick = makePayment;- *note: here we don't use parenthesis with the method name( not - makePayment(), just- makePayment)- To remove the handler, - paymentButton.onclick = null;
- Using - addEventListnermethod - allows to add multiple eventListeners by calling the method multiple times on the element- let paymentButton = document.querySelector('#paymentSubmit'); paymentButton.addEventListner('click', makePayment);- With this, we can remove the event listener using - removeEventListnermethod:
Event Object
On occurrence of an event, the browser would create an Event object and pass it as first argument to the event handler function. This Event object carries details of the event, it would have properties depending on the type of the event, below are some common properties
- type: type of the event -- clickor- keyupor- mouseoutetc
- target: See in event bubbling
- currentTarget: See in event bubbling
- clientX/clientY: pixel coordinates of the mouse position that triggered the event if its a mouse event.
Last updated