A Beginner's Guide to Event Handling in JavaScript

Take a look at the following example. Run the CodePen demo and click the button that says "Click me". An alert box should pop up.

Open demo in new tab

So what exactly is happening here? Here is the code that achieved this behavior:

html
1<button onclick="success()">Click me</button>

The onclick attribute inside the <button> element is called an event handler. When the <button> receives the "click" event, it will execute the success() function, which is defined in the JavaScript file.

javascript
1function success() {
2  alert("Success!");
3}

When the success() function is executed, it will call the built-in function alert(), which tells your browser to create an alert box with the specified content.

What is an event

So what exactly is an event?

An event is a user input, a signal from the user to the DOM node. This signal could be a click, a pointer hover, a scroll action, and so on. We will discuss more about the different types of events in the next lesson.

Wait, there is more!

You need an account to access the rest of this lesson. Our course is 50% off for limited time only! Don't miss the opportunity!

🎉 Create an Account 🎉