codegurukool.com · Free coding tutorials & online compiler

Home › JavaScript Tutorial › Events

Events

React to clicks, typing and more.

addEventListener runs your function when something happens. The event object tells you the details.

Commands in this lesson

addEventListener

Definition: Runs a function when an event happens on an element.

Syntax:

element.addEventListener("event", function);

Example:

document.body.addEventListener("click", function(){
  console.log("clicked");
});

Example code

<button id="b">Click me</button>
<p id="c">0 clicks</p>
<script>
  let n = 0;
  b.addEventListener("click", () => { n++; c.textContent = n + " clicks"; });
</script>

Run this code in the online editor

← The DOMArrays and loops →