click

If the user has a mouse, they will surely click the cursor on the page.

Time to read: less than 5 min

Briefly

Event of clicking on an HTML element. When the user clicks the mouse on the page, the browser determines on which element the click occurred and creates a click event.

You can subscribe to events and execute JavaScript code when the event occurs.

How to write

Subscribe to all clicks on the page:

        
          
          document.addEventListener('click', function () {  alert('You clicked on the page!')})
          document.addEventListener('click', function () {
  alert('You clicked on the page!')
})

        
        
          
        
      

Subscribe only to clicks on the button (it must be on the page):

        
          
          const button = document.getElementsByTagName('button')[0]// attaching the handler to the click eventbutton.addEventListener('click', function () {  alert('You clicked on the button!')})
          const button = document.getElementsByTagName('button')[0]

// attaching the handler to the click event
button.addEventListener('click', function () {
  alert('You clicked on the button!')
})

        
        
          
        
      

How to understand

Read more about the event mechanism in the article "Events".

The handler function also receives an event object, which contains additional information about the click. The most useful properties:

  • detail — the number of clicks made by the user. 1 — for a single click, 2 — for double, and so on.
  • view — returns the window object in which the event occurred.

To access the event object, the handler function must take a parameter:

        
          
          button.addEventListener('click', function (event) {  // Prints the number of clicks  alert(event.detail)})
          button.addEventListener('click', function (event) {
  // Prints the number of clicks
  alert(event.detail)
})

        
        
          
        
      

Example using these properties:

Open demo in the new window

In practice

Advice 1

🛠 There is a nuance with clicks. If a user pressed the mouse button, moved the cursor out of the element, and then released the button, the click event will not occur.

🛠 You can handle clicks on any HTML elements: <div>, <p>, <button> — browsers can do this.

🛠 Some mobile browsers (for example, Safari Mobile) generate click events only on interactive elements — <button>, <a>, <img>, <input> and so on.

🛠 Mobile browsers also generate the touch event.