How to trigger event in JavaScript?

前端 未结 18 1911
情深已故
情深已故 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: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.

提交回复
热议问题