How to trigger event in JavaScript?

前端 未结 18 1906
情深已故
情深已故 2020-11-21 04:48

I have attached an event to a text box using addEventListener. It works fine. My problem arose when I wanted to trigger the event programmatically from another

相关标签:
18条回答
  • 2020-11-21 05:02

    Use jquery event call. Write the below line where you want to trigger onChange of any element.

    $("#element_id").change();
    

    element_id is the ID of the element whose onChange you want to trigger.

    Avoid the use of

     element.fireEvent("onchange");
    

    Because it has very less support. Refer this document for its support.

    0 讨论(0)
  • 2020-11-21 05:04

    If you don't want to use jQuery and aren't especially concerned about backwards compatibility, just use:

    let element = document.getElementById(id);
    element.dispatchEvent(new Event("change")); // or whatever the event type might be
    

    See the documentation here and here.

    EDIT: Depending on your setup you might want to add bubbles: true:

    let element = document.getElementById(id);
    element.dispatchEvent(new Event('change', { 'bubbles': true }));
    
    0 讨论(0)
  • 2020-11-21 05:07

    The accepted answer didn’t work for me, none of the createEvent ones did.

    What worked for me in the end was:

    targetElement.dispatchEvent(
        new MouseEvent('click', {
            bubbles: true,
            cancelable: true,
            view: window,
    }));
    

    Here’s a snippet:

    const clickBtn = document.querySelector('.clickme');
    const viaBtn = document.querySelector('.viame');
    
    viaBtn.addEventListener('click', function(event) {
        clickBtn.dispatchEvent(
            new MouseEvent('click', {
                bubbles: true,
                cancelable: true,
                view: window,
        }));
    });
    
    clickBtn.addEventListener('click', function(event) {
        console.warn(`I was accessed via the other button! A ${event.type} occurred!`);
    });
    <button class="clickme">Click me</button>
    
    <button class="viame">Via me</button>

    From reading: https://developer.mozilla.org/en-US/docs/Web/API/MouseEvent

    0 讨论(0)
  • 2020-11-21 05:08

    A working example:

    // Add an event listener
    document.addEventListener("name-of-event", function(e) {
      console.log(e.detail); // Prints "Example of an event"
    });
    
    // Create the event
    var event = new CustomEvent("name-of-event", { "detail": "Example of an event" });
    
    // Dispatch/Trigger/Fire the event
    document.dispatchEvent(event);
    

    For older browsers polyfill and more complex examples, see MDN docs.

    See support tables for EventTarget.dispatchEvent and CustomEvent.

    0 讨论(0)
  • 2020-11-21 05:08

    if you use jQuery, you can simple do

    $('#yourElement').trigger('customEventName', [arg0, arg1, ..., argN]);
    

    and handle it with

    $('#yourElement').on('customEventName',
       function (objectEvent, [arg0, arg1, ..., argN]){
           alert ("customEventName");
    });
    

    where "[arg0, arg1, ..., argN]" means that these args are optional.

    0 讨论(0)
  • 2020-11-21 05:08

    Just to suggest an alternative that does not involve the need to manually invoke a listener event:

    Whatever your event listener does, move it into a function and call that function from the event listener.

    Then, you can also call that function anywhere else that you need to accomplish the same thing that the event does when it fires.

    I find this less "code intensive" and easier to read.

    0 讨论(0)
提交回复
热议问题