What are events in JavaScript?
An event is when an HTML element experiences a change in its state due to an activity performed by a user or the browser. These events are attached to elements in the Document Object Model (
JavaScript code executes responses to events in a process known as event handling. The code itself, in this case, is known as the event handler. An instance of event handling is closing a pop-up window on a user's click on the button provided to close the pop-up window. Thus, JavaScript helps make the interface of a web page responsive to events.
Note: Event handlers are also sometimes called event listeners. However, they have a slight difference. Event listeners listen for any events while event handlers execute the response to that event.
Syntax
The intersection of HTML elements with JavaScript event handlers follows a general format, as shown below:
<element event="JavaScript code or call to a function">
Let's look at some popular event types in detail.
Example one: The onclick event type
The onclick event type triggers on a mouse click. The code below shows how to use it to trigger an alert in the user's browser:
Explanation
- Line 3: We set the
typeattribute in the<script>tag totext/javascriptsince we use the JavaScript media type. - Lines 4–7: The
eventHandler()function raises an alert message in the browser window. - Line 12: The
onclickattribute in the<button>tag executes theeventHandler()function.
Example two: The onmouseover event type
The onmouseover event type is triggered when the mouse passes over an HTML element. The code below shows how to use it to change the color of a box:
Explanation
- Line 3: We set the
typeattribute in the<script>tag totext/javascriptsince we use the JavaScript media type. - Lines 4–8: The
eventHandler()function gets the element withidset toboxand changes the color of theboxfromredtoblue. - Line 16: The
onmouseoverattribute in the<div>tag executes theeventHandler()function.
Example three: The onkeyup event type
The onkeyup event type is triggered when the user releases a key after pressing it. The code below shows how to use it to trigger an alert in the user's browser:
Explanation
- Line 3: We set the
typeattribute in the<script>tag totext/javascriptsince we use the JavaScript media type. - Lines 4–7: The
eventHandler()function raises an alert message in the browsers window when a user presses a key for writing something in the provided text box.. - Line 14: The
onkeyupattribute in the<input>tag executes theeventHandler()function.
Note: To find more event types in JavaScript, please refer to the official documentation.
Free Resources