How to Check if an Event has been Triggered in Javascript

In javascript, events are actions that occur when something happens on a web page, such as a user clicking a button, scrolling the page, or typing into a form. In order to check if an event has been triggered, we can use event listeners in our Javascript code.

Event listeners are functions that get executed when a specific event occurs. They can be added to an HTML element using the addEventListener() method. In the following example, we will add an event listener to a button element, and check if the button has been clicked.

HTML:

  • We have an HTML file with a single button element.
  • We have also included our Javascript file script.js with a script tag at the bottom.
<!DOCTYPE html>
<html>
  <head>
    <title>Check if event has been triggered</title>
  </head>
  <body>
    <button id="myButton">Click me!</button>
    <script src="script.js"></script>
  </body>
</html>

Javascript:

  • We have selected the button element using document.querySelector() method and stored it in the button variable.
  • We have added an event listener to the button element using the addEventListener() method.
  • In the event listener function, we have logged a message to the console to indicate that the button has been clicked.
// select the button element
const button = document.querySelector('#myButton');

// add an event listener to the button element
button.addEventListener('click', function() {
  // log a message to the console to indicate that the button has been clicked
  console.log('Button has been clicked!');
});

When the button is clicked, the event listener function will be executed, and the message Button has been clicked! will be logged to the console. This indicates that the event has been triggered.

To summarize, we can check if an event has been triggered in Javascript by adding an event listener to the HTML element, and executing a function when the event occurs. The function can then perform any necessary actions, such as logging a message to the console or updating the page content.