Click event tutorial

Click event tutorial how to register an event handler for a click event.

Click event

The click event is raised when the user clicks on an element. It fires after the mousedown and mouseup events, in that order.

An event handler must be registered for an event with addEventListener().

Click event example

The following example registers an event handler for a click event.

<!DOCTYPE html>
<html lang="en">

    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Click event</title>
    <link rel="stylesheet" href="main.css">


    <div id="output"></div>

    <script src="main.js"></script>


In the example, we have register a click event handler for the body element. We show the coordinates of the mouse pointer in the output div.

body {
    height: 100vh;
    padding: 6px;
    border: 1px solid steelblue;

This is some styling. Note that in order for the example to work, we must set a height for the body.

const el = document.body;
const output = document.getElementById('output');


el.addEventListener('click', e => {

    output.innerHTML = `x: ${e.x} y: ${e.y}`;

In the code, we register a click event handler for the body element. When the user clicks on the body of the document, the x and y coordinates of the mouse pointer are outputted.

output.innerHTML = `x: ${e.x} y: ${e.y}`;

An event object is generated for the click event. We can get some information about the event from the event object. In our case, we get the x and y coordinates.

In this tutorial, we have shown how to work with a click event.

You might also be interested in the following related tutorials: JavaScript queryselector tutorial, Document.all tutorial, Element.classList tutorial, Element.innerHtml tutorial, Document.createNodeIterator tutorial, Document.getElementById tutorial, or Counting child elements in DOM.