DEV Community

Manikanta Yarramsetti
Manikanta Yarramsetti

Posted on

JavaScript Events Simply Explained With Real Code Examples

I remember when I started JavaScript, events confused me a lot.

Not because they are hard. Just because nobody explained it simply.

So let me try.

Okay so what is an event

An event is just something the user does on your page.

Clicked a button. Typed in a box. Pressed a key. Submitted a form.
Scrolled down. All of these are events.

JavaScript lets you watch for these things and do something when
they happen. That is the whole idea.

The basic way to listen

const btn = document.getElementById("myBtn");

btn.addEventListener("click", function() {
  console.log("someone clicked the button");
});
Enter fullscreen mode Exit fullscreen mode

Three things here. The element. The event name. The function to run.

That is the pattern you will use everywhere.

There is also an event object

When something happens the browser gives you an object with all
the details about it. Most people call it e or event.

btn.addEventListener("click", function(e) {
  console.log(e.target);  // what got clicked
  console.log(e.type);    // "click"
});
Enter fullscreen mode Exit fullscreen mode

You do not always need it but it is always there if you want it.

Events you will use all the time

click — someone clicks something

btn.addEventListener("click", function() {
  console.log("clicked");
});
Enter fullscreen mode Exit fullscreen mode

input — someone is typing in a field

const box = document.getElementById("searchBox");

box.addEventListener("input", function(e) {
  console.log(e.target.value);
});
Enter fullscreen mode Exit fullscreen mode

This fires every time they type a character. Really useful for
live search or character counters.

submit — someone submits a form

const form = document.getElementById("myForm");

form.addEventListener("submit", function(e) {
  e.preventDefault();
  console.log("form submitted");
});
Enter fullscreen mode Exit fullscreen mode

The e.preventDefault() stops the page from refreshing.
You almost always need this on forms.

keydown — someone presses a key

document.addEventListener("keydown", function(e) {
  if (e.key === "Enter") {
    console.log("enter was pressed");
  }
});
Enter fullscreen mode Exit fullscreen mode

mouseover — someone hovers over an element

const card = document.getElementById("card");

card.addEventListener("mouseover", function() {
  card.style.background = "lightblue";
});
Enter fullscreen mode Exit fullscreen mode

What is preventDefault

When you submit a form the browser reloads the page by default.
When you click a link it goes somewhere by default.

preventDefault stops that from happening so you can handle it
yourself with JavaScript.

link.addEventListener("click", function(e) {
  e.preventDefault();
  console.log("stopped the link from going anywhere");
});
Enter fullscreen mode Exit fullscreen mode

You will use this a lot.

Event bubbling

This one is a bit different but worth knowing.

Say you have a button inside a div. You click the button.
The click fires on the button first then travels up to the div
then to the body and keeps going up.

document.getElementById("myDiv").addEventListener("click", function() {
  console.log("div clicked");
});

document.getElementById("myBtn").addEventListener("click", function() {
  console.log("button clicked");
});

// click the button and you see both
// button clicked
// div clicked
Enter fullscreen mode Exit fullscreen mode

If you want to stop it going up just use stopPropagation.

btn.addEventListener("click", function(e) {
  e.stopPropagation();
  console.log("stays here, does not go up");
});
Enter fullscreen mode Exit fullscreen mode

A real small example

Let me put it all together in something you can actually run.

<!DOCTYPE html>
<html>
<body>

  <input id="nameInput" placeholder="type your name" />
  <button id="greetBtn">Say Hello</button>
  <p id="result"></p>

  <script>
    const input = document.getElementById("nameInput");
    const btn = document.getElementById("greetBtn");
    const result = document.getElementById("result");

    btn.addEventListener("click", function() {
      const name = input.value.trim();

      if (name === "") {
        result.textContent = "type your name first";
        return;
      }

      result.textContent = "hello " + name + "!";
    });

    input.addEventListener("keydown", function(e) {
      if (e.key === "Enter") {
        btn.click();
      }
    });
  </script>

</body>
</html>
Enter fullscreen mode Exit fullscreen mode

Type a name, click the button or just press Enter.
Both work because we listened for two different events.

Honestly that is all you need to start

Click, input, submit, keydown. Learn these four first.

Everything else like drag events, touch events, scroll events,
they all follow the exact same pattern. Once you get the idea
the rest is easy to pick up.

Just start building small things and you will get it fast.


Top comments (0)