Javascript вызвать событие click

Dispatching custom events

We can not only assign handlers, but also generate events from JavaScript.

Custom events can be used to create “graphical components”. For instance, a root element of our own JS-based menu may trigger events telling what happens with the menu: open (menu open), select (an item is selected) and so on. Another code may listen for the events and observe what’s happening with the menu.

We can generate not only completely new events, that we invent for our own purposes, but also built-in ones, such as click , mousedown etc. That may be helpful for automated testing.

Event constructor

Built-in event classes form a hierarchy, similar to DOM element classes. The root is the built-in Event class.

We can create Event objects like this:

let event = new Event(type[, options]);
  • type – event type, a string like «click» or our own like «my-event» .
  • options – the object with two optional properties:
    • bubbles: true/false – if true , then the event bubbles.
    • cancelable: true/false – if true , then the “default action” may be prevented. Later we’ll see what it means for custom events.

    dispatchEvent

    After an event object is created, we should “run” it on an element using the call elem.dispatchEvent(event) .

    Then handlers react on it as if it were a regular browser event. If the event was created with the bubbles flag, then it bubbles.

    In the example below the click event is initiated in JavaScript. The handler works same way as if the button was clicked:

      

    There is a way to tell a “real” user event from a script-generated one.

    The property event.isTrusted is true for events that come from real user actions and false for script-generated events.

    Bubbling example

    We can create a bubbling event with the name «hello» and catch it on document .

    All we need is to set bubbles to true :

     

    1. We should use addEventListener for our custom events, because on only exists for built-in events, document.onhello doesn’t work.
    2. Must set bubbles:true , otherwise the event won’t bubble up.

    The bubbling mechanics is the same for built-in ( click ) and custom ( hello ) events. There are also capturing and bubbling stages.

    MouseEvent, KeyboardEvent and others

    Here’s a short list of classes for UI Events from the UI Event specification:

    • UIEvent
    • FocusEvent
    • MouseEvent
    • WheelEvent
    • KeyboardEvent

    We should use them instead of new Event if we want to create such events. For instance, new MouseEvent(«click») .

    The right constructor allows to specify standard properties for that type of event.

    Like clientX/clientY for a mouse event:

    let event = new MouseEvent("click", < bubbles: true, cancelable: true, clientX: 100, clientY: 100 >); alert(event.clientX); // 100

    Please note: the generic Event constructor does not allow that.

    let event = new Event("click", < bubbles: true, // only bubbles and cancelable cancelable: true, // work in the Event constructor clientX: 100, clientY: 100 >); alert(event.clientX); // undefined, the unknown property is ignored!

    Technically, we can work around that by assigning directly event.clientX=100 after creation. So that’s a matter of convenience and following the rules. Browser-generated events always have the right type.

    The full list of properties for different UI events is in the specification, for instance, MouseEvent.

    Custom events

    For our own, completely new events types like «hello» we should use new CustomEvent . Technically CustomEvent is the same as Event , with one exception.

    In the second argument (object) we can add an additional property detail for any custom information that we want to pass with the event.

     

    The detail property can have any data. Technically we could live without, because we can assign any properties into a regular new Event object after its creation. But CustomEvent provides the special detail field for it to evade conflicts with other event properties.

    Besides, the event class describes “what kind of event” it is, and if the event is custom, then we should use CustomEvent just to be clear about what it is.

    event.preventDefault()

    Many browser events have a “default action”, such as navigating to a link, starting a selection, and so on.

    For new, custom events, there are definitely no default browser actions, but a code that dispatches such event may have its own plans what to do after triggering the event.

    By calling event.preventDefault() , an event handler may send a signal that those actions should be canceled.

    In that case the call to elem.dispatchEvent(event) returns false . And the code that dispatched it knows that it shouldn’t continue.

    Let’s see a practical example – a hiding rabbit (could be a closing menu or something else).

    Below you can see a #rabbit and hide() function that dispatches «hide» event on it, to let all interested parties know that the rabbit is going to hide.

    Any handler can listen for that event with rabbit.addEventListener(‘hide’. ) and, if needed, cancel the action using event.preventDefault() . Then the rabbit won’t disappear:

    o<>

    Please note: the event must have the flag cancelable: true , otherwise the call event.preventDefault() is ignored.

    Events-in-events are synchronous

    Usually events are processed in a queue. That is: if the browser is processing onclick and a new event occurs, e.g. mouse moved, then its handling is queued up, corresponding mousemove handlers will be called after onclick processing is finished.

    The notable exception is when one event is initiated from within another one, e.g. using dispatchEvent . Such events are processed immediately: the new event handlers are called, and then the current event handling is resumed.

    For instance, in the code below the menu-open event is triggered during the onclick .

    It’s processed immediately, without waiting for onclick handler to end:

     

    The output order is: 1 → nested → 2.

    Please note that the nested event menu-open is caught on the document . The propagation and handling of the nested event is finished before the processing gets back to the outer code ( onclick ).

    That’s not only about dispatchEvent , there are other cases. If an event handler calls methods that trigger other events – they are processed synchronously too, in a nested fashion.

    Let’s say we don’t like it. We’d want onclick to be fully processed first, independently from menu-open or any other nested events.

    Then we can either put the dispatchEvent (or another event-triggering call) at the end of onclick or, maybe better, wrap it in the zero-delay setTimeout :

     

    Now dispatchEvent runs asynchronously after the current code execution is finished, including menu.onclick , so event handlers are totally separate.

    The output order becomes: 1 → 2 → nested.

    Summary

    To generate an event from code, we first need to create an event object.

    The generic Event(name, options) constructor accepts an arbitrary event name and the options object with two properties:

    • bubbles: true if the event should bubble.
    • cancelable: true if the event.preventDefault() should work.

    Other constructors of native events like MouseEvent , KeyboardEvent and so on accept properties specific to that event type. For instance, clientX for mouse events.

    For custom events we should use CustomEvent constructor. It has an additional option named detail , we should assign the event-specific data to it. Then all handlers can access it as event.detail .

    Despite the technical possibility of generating browser events like click or keydown , we should use them with great care.

    We shouldn’t generate browser events as it’s a hacky way to run handlers. That’s bad architecture most of the time.

    Native events might be generated:

    • As a dirty hack to make 3rd-party libraries work the needed way, if they don’t provide other means of interaction.
    • For automated testing, to “click the button” in the script and see if the interface reacts correctly.

    Custom events with our own names are often generated for architectural purposes, to signal what happens inside our menus, sliders, carousels etc.

    Источник

    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.

    Источник

    Читайте также:  Java if null set default value
Оцените статью