DEV Community

DIWAKARKASHYAP
DIWAKARKASHYAP

Posted on

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

Top comments (0)