How to: Add an event listener in vanilla JavaScript
Resources
CodePen Demo:
Adding an event listener in vanilla JavaScript can come in handy, especially when you don’t want to add in an additional JavaScript library, such as jQuery. To follow along, I’d recommend using either JSFiddle or CodePen so you can see your changes in real-time.
In this example, we’ll use this HTML:
Here’s how you can add an event listener:
Note: the style shown for the button uses arrow functions, which are part of ES6.
Now that you’ve added the JavaScript, if you click the button, you should see the message “Hello, world!” displayed in an alert.