Chapter 17. Assigning Event Handlers with HTML Attributes
The previous lesson introduced you to many events that you can handle in your JavaScript code. That leads to the question "How do you handle events in JavaScript?"
The answer isn't as straightforward as most would like. There are many ways you can "wire up" JavaScript code to handle an event, and over the course of this lesson, and those following, you'll learn the many ways you can set up functions to handle events.
You'll start this journey by learning how to use HTML attributes to handle events. Admittedly, HTML attribute event handlers aren't used as often as they used to be, but they are very useful when you need to handle an event quickly.
WIRING UP EVENT HANDLERS
Let's start with an example element. Following is a normal <div/>
element:
<div id="myDiv">Hello, Events!</div>
This element has an id
of myDiv
, and it contains a small bit of text. It's an ordinary element now, but you can add some specialness to it by handling the click
event. To handle this event, add an attribute called onclick
to the opening tag, like this:
<div id="myDiv" onclick="">Hello, Events!</div>
The name of an attribute used to handle events is the word on
followed by the name of the event. In this example the event handler onclick
handles the click
event. If you wanted to handle the mouseover
event, the attribute's name would be onmouseover
.
Also keep in mind that even though <div/>
elements don't interact with mouse clicks by default, you can add that ...
Get JavaScript® 24-Hour Trainer now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.