DEV Community

kirthinandi
kirthinandi

Posted on

What Are JavaScript Events?

JavaScript Events

JavaScript events can be defined as something the user does in a website or browser. This can be a multitude of different things such as clicking a button, closing the browser, hovering over an element on the browser, etc.

Image-description

Event Listeners

JavaScript is capable of detecting or listening for the events taking place in a browser. For example, when a user clicks on a specific button, JavaScript can pay attention to the user's click and do something after the click like displaying text or an image.

To tell JavaScript to listen for an event, we can use the method, addEventListener(), on an element.

eventTarget.addEventListener('click', function() {
   console.log('You clicked me!');
});
Enter fullscreen mode Exit fullscreen mode

In the example above, the addEventListener() is being added onto the element we select. This can be a button we have created like the example below, a variable containing the wanted element, etc.

const button = document.createElement('button');
button.addEventListener('click', function() {
   console.log('You clicked me!');
});
Enter fullscreen mode Exit fullscreen mode

The event listener takes in two arguments with the first being the event we want JavaScript to listen for. In this case, it was the 'click' event but it can be a mouseover, keydown, drag, scroll, or any of the other various DOM events. The second argument is the function which tells JavaScript what to do once the event has been completed. In the example above, the browser's console will print the statement, 'You clicked me!'

Now, that you have learned the basics of JavaScript events and using event listeners, you can try to create your own event and event listener!

Image description

Top comments (2)

Collapse
 
andrewbaisden profile image
Andrew Baisden

Nice introduction to the topic.

Collapse
 
kirthinandi profile image
kirthinandi

Thank you!