Triggering events in javascript

How to Create and Trigger Event in JavaScript

This tutorial is aimed to teach you the right techniques to create and trigger DOM events (also called synthetic events).

You can create events with the Event constructor like in the following example which uses the EventTarget.dispatchEvent() method:

html> html> head> title>Title of the document title> head> body> h1 id="elemId">Welcome to W3Docs h1> script> document.addEventListener("welcome", function(event) < alert("Hi, " + event.target.tagName); // Hi H1 >); let event = new Event("welcome", < bubbles: true >); elemId.dispatchEvent(event); script> body> html>

The addEventListener() initializes a function that will be called whenever the defined event is dispatched to the target.

To append additional data to the event object, you can use the CustomEvent interface and the detail property to pass custom data:

let event = new CustomEvent('eventName', < detail: elem.prop.name >);

Then you can access the specified additional data in the event listener by using the following code:

html> html> head> title>Title of the document title> head> body> h1 id="elemId">Welcome to W3Docs h1> script> elemId.addEventListener("welcome", function(event) < alert(event.detail.name); >); elemId.dispatchEvent(new CustomEvent("welcome", < detail: < name: "W3Docs" > >)); script> body> html>

It is often recommended to trigger an event from a child element:

html> html> head> title>Title of the document title> head> body> input type="text"> input> script> let text = document.querySelector('input'); const eventAwesome = new CustomEvent('awesome', < bubbles: true, detail: < text: () => text.value > >); text.addEventListener('awesome', e => alert(e.detail.text())); text.addEventListener('input', e => e.target.dispatchEvent(eventAwesome)); script> body> html>

To create and dispatch events dynamically you can use the following code:

html> html> head> title>Title of the document title> head> body> input type="text"> textarea> script> let inputText = document.querySelector('input'); inputText.addEventListener('awesome', e => alert(e.detail.text())); inputText.addEventListener('input', function( ) < this.dispatchEvent(new CustomEvent('awesome', < bubbles: true, detail: < text: () => inputText.value > >)) >); script> body> html>

The dispatchEvent

The dispatchEvent delivers an Event at the specified EventTarget, synchronously executing the affected EventListeners in an appropriate order. Unlike native events that are fired by the DOM and call event handlers asynchronously with the help of the event loop, the dispatchEvent execute event handlers synchronously.

Читайте также:  Задать значение переменной python

Источник

Creating and triggering events

This article demonstrates how to create and dispatch DOM events. Such events are commonly called synthetic events, as opposed to the events fired by the browser itself.

Creating custom events

Events can be created with the Event constructor as follows:

const event = new Event("build"); // Listen for the event. elem.addEventListener( "build", (e) =>  /* … */ >, false, ); // Dispatch the event. elem.dispatchEvent(event); 

The above code example uses the EventTarget.dispatchEvent() method.

This constructor is supported in most modern browsers. For a more verbose approach, see the old-fashioned way below.

Adding custom data – CustomEvent()

To add more data to the event object, the CustomEvent interface exists and the detail property can be used to pass custom data. For example, the event could be created as follows:

const event = new CustomEvent("build",  detail: elem.dataset.time >); 

This will then allow you to access the additional data in the event listener:

function eventHandler(e)  console.log(`The time is: $e.detail>`); > 

The old-fashioned way

The older approach to creating events uses APIs inspired by Java. The following shows an example with document.createEvent() :

// Create the event. const event = document.createEvent("Event"); // Define that the event name is 'build'. event.initEvent("build", true, true); // Listen for the event. elem.addEventListener( "build", (e) =>  // e.target matches elem >, false, ); // target can be any Element or other EventTarget. elem.dispatchEvent(event); 

Event bubbling

It is often desirable to trigger an event from a child element, and have an ancestor catch it; optionally, with data:

form> textarea>textarea> form> 
const form = document.querySelector("form"); const textarea = document.querySelector("textarea"); // Create a new event, allow bubbling, and provide any data you want to pass to the "detail" property const eventAwesome = new CustomEvent("awesome",  bubbles: true, detail:  text: () => textarea.value >, >); // The form element listens for the custom "awesome" event and then consoles the output of the passed text() method form.addEventListener("awesome", (e) => console.log(e.detail.text())); // As the user types, the textarea inside the form dispatches/triggers the event to fire, and uses itself as the starting point textarea.addEventListener("input", (e) => e.target.dispatchEvent(eventAwesome)); 

Creating and dispatching events dynamically

Elements can listen for events that haven’t been created yet:

form> textarea>textarea> form> 
const form = document.querySelector("form"); const textarea = document.querySelector("textarea"); form.addEventListener("awesome", (e) => console.log(e.detail.text())); textarea.addEventListener("input", function ()  // Create and dispatch/trigger an event on the fly // Note: Optionally, we've also leveraged the "function expression" (instead of the "arrow function expression") so "this" will represent the element this.dispatchEvent( new CustomEvent("awesome",  bubbles: true, detail:  text: () => textarea.value >, >), ); >); 

Triggering built-in events

This example demonstrates simulating a click (that is programmatically generating a click event) on a checkbox using DOM methods. View the example in action.

function simulateClick()  const event = new MouseEvent("click",  view: window, bubbles: true, cancelable: true, >); const cb = document.getElementById("checkbox"); const cancelled = !cb.dispatchEvent(event); if (cancelled)  // A handler called preventDefault. alert("cancelled"); > else  // None of the handlers called preventDefault. alert("not cancelled"); > > 

See also

Found a content problem with this page?

This page was last modified on Jul 19, 2023 by MDN contributors.

Your blueprint for a better internet.

Источник

Triggering built-in and custom events using JavaScript

There are different ways to trigger an event on an HTML element in JavaScript. Some elements provide built-in methods for triggering different kinds of events.

For example, to trigger a click event on any HTML element, you can use the click() method of the element DOM object:

const btn = document.querySelector('button'); btn.click(); 

Similarly, the and HTML elements provide the focus() and blur() methods to trigger the focus and blur events:

const input = document.querySelector('input'); // Focus input element input.focus(); // Blur input element input.blur(); 

The element offers the submit() and reset() methods for triggering the submit() and reset events:

const form = document.querySelector('form'); // Trigger submit event form.submit(); // Trigger reset event form.reset(); 

To trigger other events such as the change or keyup , you need to create an Event object and pass it to the dispatchEvent() method of the element object as shown below:

const select = document.querySelector('select'); // Listen for change event select.addEventListener('change', (e) =>  console.log(`A new value is selected.`); >); // Programmatically trigger `change` event const event = new Event('change'); select.dispatchEvent(event); 

In the above example, we first registered an event handler to the change event of the element, then created a new event by using the Event constructor, and finally used the dispatchEvent() method to trigger the change event.

// Listen for `hello` event select.addEventListener('hello', (e) =>  console.log(`Hey there!`); >); // Programmatically trigger `hello` event const event = new Event('hello'); select.dispatchEvent(event); 

To pass more data to the event object, You can use the CustomEvent() constructor instead. It accepts an optional object as a second parameter that can be used to define event properties. The detail property of the optional object can be used to pass custom data. Let us say you have the following

time data-time="2020-09-29T13:58:25.546Z">Sep 29th, 2020time> 

The following example demonstrates how you can trigger a custom event called buildTime and pass additional data to the event object:

// Define an event handler const handler = (e) =>  console.log(`Build time is $e.detail>`); >; // Listen for `buildTime` custom event document.addEventListener('buildTime', handler); // Trigger `buildTime` custom event const time = document.querySelector('time'); const event = new CustomEvent('buildTime',  detail: time.dataset.time >); document.dispatchEvent(event); 

The Event constructor works in all modern browsers except Internet Explorer. To support old browsers like IE9+, you can use the document.createEvent() method to create an trigger an event as shown below:

const elem = document.querySelector('button'); // Define an event handler const handler = (e) =>  console.log(`Event is triggered!`); >; // Listen for `awesome` event elem.addEventListener('awesome', handler); // Create an event - IE9+ const event = document.createEvent('Event'); // Define the event name event.initEvent('awesome', false, true); // Trigger `awesome` event elem.dispatchEvent(event); 

Sometimes you may want to trigger an event from the child element and capture it on a parent element. To do so, just set the bubbles property to true . Let us say you have the following HTML code snippet:

form> input type="text" name="name"> form> 
const form = document.querySelector('form'); const input = document.querySelector('input'); // Create a new event with bubbling allowed const event = new CustomEvent('name',  bubbles: true, detail:  text: () => input.value > >); // Listen for `name` event on form form.addEventListener('name', (e) =>  console.log(`My name is $e.detail.text()>`); >); // Trigger `name` event from input when the user types input.addEventListener('keyup', (e) =>  e.target.dispatchEvent(event); >); 

You might also like.

Источник

Оцените статью