To react on events we can assign a handler – a function that runs in case of an event.
We can set event handlers using:
HTML Attributes: A handler can be set in HTML with an attribute named on<event>.
DOM property: We can assign a handler using a DOM property on<event>.
Methods event listeners. Explained in next slide
Event Handlers
Handlers are a way to run JavaScript code in case of user actions. There are several ways to assign a handler. Let’s see them, starting from the simplest one.
For instance, to assign a click handler for an input, we can use onclick, like here: On mouse click, the code inside onclick runs.
Please note that inside onclick we use single quotes, because the attribute itself is in double quotes. If we forget that the code is inside the attribute and use double quotes inside, like this: onclick=”alert(“Click!”)”, then it won’t work right.
An HTML-attribute is not a convenient place to write a lot of code, so we’d better create a JavaScript function and call it there.
As we know, HTML attribute names are not case-sensitive, so ONCLICK works as well as onClick and onCLICK… But usually attributes are lowercased: onclick.
If the handler is assigned using an HTML-attribute then the browser reads it, creates a new function from the attribute content and writes it to the DOM property.