O'Reilly logo

JavaScript® 24-Hour Trainer by Jeremy McPeak

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

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 ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required