How to trigger event in JavaScript?

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

    Modified @Dorian's answer to work with IE:

    document.addEventListener("my_event", function(e) {
      console.log(e.detail);
    });
    
    var detail = 'Event fired';
    
    try {
    
        // For modern browsers except IE:
        var event = new CustomEvent('my_event', {detail:detail});
    
    } catch(err) {
    
      // If IE 11 (or 10 or 9...?) do it this way:
    
        // Create the event.
        var event = document.createEvent('Event');
        // Define that the event name is 'build'.
        event.initEvent('my_event', true, true);
        event.detail = detail;
    
    }
    
    // Dispatch/Trigger/Fire the event
    document.dispatchEvent(event);
    

    FIDDLE: https://jsfiddle.net/z6zom9d0/1/

    SEE ALSO:
    https://caniuse.com/#feat=customevent

提交回复
热议问题