Event handlers
Event Handlers
3 ways to add event handler to an HTML element:
using the HTML attribute e.g.
onclickoronmouseover<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(), justmakePayment)To remove the handler,
paymentButton.onclick = null;Using
addEventListnermethod - allows to add multiple eventListeners by calling the method multiple times on the elementlet 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 -clickorkeyupormouseoutetctarget: See in event bubblingcurrentTarget: See in event bubblingclientX/clientY: pixel coordinates of the mouse position that triggered the event if its a mouse event.
Last updated