From the course: HTML for Programmers

Unlock the full course today

Join today to access over 24,800 courses taught by industry experts.

Attach JavaScript events to HTML elements

Attach JavaScript events to HTML elements

From the course: HTML for Programmers

Attach JavaScript events to HTML elements

- [Instructor] Sometimes you may want to attach event listeners to Dominos like adding an on click event listener to a button. There are three primary ways to add event listeners, inline on the HTML element, using the onX attribute directly on an node. We're using the addEventListener. Let's say we have a button that when clicked, will open an alert dialogue. We can add an on click attribute to the button element that triggers an alert. Let's look at method two for adding an event listener. First, let's get a handle on our button node. I'll add an ID so it's easy to query for the node. Next, we can use querySelector to grab the button and directly set the onClick handler. The value will be the alert function. The last method is to use addEventListener. This takes two arguments, the event to listen for and the function or functionality to execute when that event has been triggered. In general, it's considered good practice…

Contents