Categories
JavaScript Answers

How to trigger event with parameters with JavaScript?

Spread the love

Sometimes, we want to trigger event with parameters with JavaScript.

In this article, we’ll look at how to trigger event with parameters with JavaScript.

How to trigger event with parameters with JavaScript?

To trigger event with parameters with JavaScript, we can trigger a custom event.

For instance, we write:

<button>
  click me
</button>

to add a button.

Then we write:

const button = document.querySelector("button");
button.addEventListener("custom-event", (e) => {
  console.log("custom-event", e.detail);
});
button.onclick = (e) => {
  const event = new CustomEvent("custom-event", {
    'detail': {
      customInfo: 10,
      customProp: 20
    }
  });
  e.target.dispatchEvent(event);
};

to select the button with querySelector.

Then we call button.addEventListener to add an event listener for the custom-event event.

We get the event data from e.detail.

Then we add a click listener to the button by setting button.onclick to a function that creates a new CustomEvent instance with the event name and some event data.

We then call e.target.dispatchEvent with event to trigger the custom-event event on the button.

Therefore, we see {customInfo: 10, customProp: 20} logged when we click the button.

Conclusion

To trigger event with parameters with JavaScript, we can trigger a custom event.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *