Code

Working With JavaScript Events

What Is An Event?

An event is a reaction to a trigger on a web page. For example, the user clicks a button, a web page has loaded, etc. An event can be triggered by the user and by the browser. The common HTML events are onclick, onchange, onmouseover, onmouseout, onkeydown, onload, onunload, onmousedown, onmouseup, etc. You can take a look at a longer list of HTML events here.

When an event occurs, you can perform a task using JavaScript code. For instance, when a button is clicked, you may want to show a message. The following code example demonstrates event handling:

See the Pen Working With Events In JavaScript by XO PIXEL (@xopixel) on CodePen.

In the code above, the text “Hello” is shown in an <h1> element when the <p> element is clicked. Here, ‘onclick’ is an event handler attribute that lets you execute JavaScript code when the <p> element is clicked. In the JavaScript code, you can specify what to do when the <p> element is clicked.

Event Handler Functions

You can easily add an event handler function to an HTML element. In the following code, the showMessage() function is called when the <p> element is clicked.

See the Pen Working With Events In JavaScript – 2 by XO PIXEL (@xopixel) on CodePen.

The following code example shows how to attach an event handler function to an HTML element using DOM (Document Object Model):

See the Pen Working With Events In JavaScript – 3 by XO PIXEL (@xopixel) on CodePen.

Useful Events

Talking about each and every JavaScript event is beyond the scope of this post. For this tutorial, I want to provide you with a few useful events that you can use for your own web development projects:

The onchange event

In the following code, when the text field is changed, the clearText() function is called and the text field is cleared.

See the Pen gWBVLO by XO PIXEL (@xopixel) on CodePen.

The onmouseover and onmouseout events

In the code below, when the user moves the mouse over the <p> element, the showMessage() function is called and the message “Good morning” is shown. And when the user moves the mouse out of the <p> element, the showMessage1() function is called and the message “Hello” is displayed.

See the Pen Working With Events In JavaScript – 5 by XO PIXEL (@xopixel) on CodePen.

The onmousedown and onmouseup events

In the following code example, when the mouse button is pressed down on the element, the showMessage() function is called and the message “Mouse down” is shown. And when the mouse button is released on the element, the showMessage1() function is called and the message “Mouse up” is displayed.

See the Pen Working With Events In JavaScript – 6 by XO PIXEL (@xopixel) on CodePen.

Like this article?

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.