Click event tutorial

last modified August 24, 2023

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 article we have shown how to work with a click event.


My name is Jan Bodnar and I am a passionate programmer with many years of programming experience. I have been writing programming articles since 2007. So far, I have written over 1400 articles and 8 e-books. I have over eight years of experience in teaching programming.