DEV Community

Cover image for What Happens When You Click? JavaScript Events Explained
Sevaki Rajasekar
Sevaki Rajasekar

Posted on

What Happens When You Click? JavaScript Events Explained

Hi everyone! Welcome to my blog. Today we are going to see another blog from my JavaScript series. Let's see the about Events with simple examples.

What is JavaScript Events?

An event is something that happens on a webpage — like:

  • A button is clicked
  • A key is pressed on the keyboard
  • A form is submitted
  • The mouse moves over something

Why do we use it?

We use events when we want the webpage to react when a user does something.
For example:
If someone clicks a button, we want to show a message or change the color.
(I hope this example will help to gain more understanding.)

Let's dive into the technical terms and real-time examples with coding:

How does it work?

  • First, we choose an element (like a button).
  • Then, we tell JavaScript to watch that element for something (like a click).
  • When that happens, we tell it to do something (like run a function). This may confuse you, let me clear with code,

Example:
Let’s say you have a button:
html

<button>Click me!</button>
Enter fullscreen mode Exit fullscreen mode

You want to show a message when someone clicks it.

Here’s the JavaScript:
Javascript

document.querySelector("button").addEventListener("click", function() {
  alert("You clicked the button!");
});
Enter fullscreen mode Exit fullscreen mode

What this does:

  • document.querySelector("button") — finds the button
  • .addEventListener("click", ...) — watches for a click
  • function() { alert(...) } — shows a message when clicked

Common HTML Events

  • onchange - An HTML element has been changed
  • onclick - The user clicks an HTML element
  • onmouseover - The user moves the mouse over an HTML element
  • onmouseout - The user moves the mouse away from an HTML element
  • onkeydown - The user pushes a keyboard key
  • onload - The browser has finished loading the page

So that's it, guys. I hope from this blog you got an idea of what is events and what it can do. So as a JavaScript learner, the introduction of "Events" gave me more ideas and understanding about a web page. So thank you for reading my blog. For more content like this, keep in touch with my blog page. Will see you in my next blog.

Reference: https://www.w3schools.com/js/js_events.asp
Credits:
Diagram: https://www.vrogue.co/post/what-is-event-loop-in-node-js-with-example-printable-templates
Cover image: https://www.guvi.in/blog/guide-for-events-in-javascript/

Top comments (0)