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.
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.
onclick
event typeThe 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:
type
attribute in the <script>
tag to text/javascript
since we use the JavaScript media type. eventHandler()
function raises an alert message in the browser window.onclick
attribute in the <button>
tag executes the eventHandler()
function.onmouseover
event typeThe 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:
type
attribute in the <script>
tag to text/javascript
since we use the JavaScript media type. eventHandler()
function gets the element with id
set to box
and changes the color of the box
from red
to blue
.onmouseover
attribute in the <div>
tag executes the eventHandler()
function.onkeyup
event typeThe 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:
type
attribute in the <script>
tag to text/javascript
since we use the JavaScript media type. eventHandler()
function raises an alert message in the browsers window when a user presses a key for writing something in the provided text box..onkeyup
attribute in the <input>
tag executes the eventHandler()
function.Note: To find more event types in JavaScript, please refer to the official documentation.
Free Resources