DEV Community

DIWAKARKASHYAP
DIWAKARKASHYAP

Posted on

2 1 1 1 1

What is Event in JS (Javascript) ?

In simple terms, an event in JavaScript refers to an action or occurrence that happens in a web page. It can be triggered by user interactions, like clicking a button or moving the mouse, or by other events such as the page finishing loading or a timer reaching a certain interval

Event handler
To act on an event, you need to add an event handler. An event handler is a piece of code that runs when an event fires.

// Get a reference to the button element
const button = document.getElementById('myButton');

// Define a function to handle the click event
function handleClick() {
  console.log('Button clicked!');
}

// Attach the event listener to the button
button.addEventListener('click', handleClick);

Enter fullscreen mode Exit fullscreen mode

In the example above, we first retrieve a reference to the button element with the ID myButton using the getElementById method. Then, we define a function handleClick that will be executed when the button is clicked. Inside the handleClick function, we log a message to the console.

Finally, we attach the event listener to the button using the addEventListener method. The first argument to addEventListener is the event type, in this case, 'click', and the second argument is the function handleClick that will be called when the click event occurs on the button.

When the button is clicked, the handleClick function will be executed, and you will see the message "Button clicked!" logged in the console.

This is just a basic example, and there are many other types of events you can handle in JavaScript, such as keypress, mouseover, submit, etc. The process of attaching event listeners and handling events is similar for different types of events, but you would change the event type and possibly the target element based on your specific requirements.

Thank you for reading this blog, follow me on Twitter, I regularly share blogs and post on Javascript, React, Web development and opensource contribution

Twitter- https://twitter.com/Diwakar_766

Github- https://github.com/DIWAKARKASHYAP

Image of Datadog

Create and maintain end-to-end frontend tests

Learn best practices on creating frontend tests, testing on-premise apps, integrating tests into your CI/CD pipeline, and using Datadog’s testing tunnel.

Download The Guide

Top comments (0)

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

πŸ‘‹ Kindness is contagious

Please leave a ❀️ or a friendly comment on this post if you found it helpful!

Okay