How to trigger event in JavaScript?

前端 未结 18 1851
情深已故
情深已故 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 04:55

    HTML

    <a href="demoLink" id="myLink"> myLink </a>
    <button onclick="fireLink(event)"> Call My Link </button>
    

    JS

    // click event listener of the link element --------------  
    document.getElementById('myLink').addEventListener("click", callLink);
    function callLink(e) {
        // code to fire
    }
    
    // function invoked by the button element ----------------
    function fireLink(event) {                   
        document.getElementById('myLink').click();      // script calls the "click" event of the link element 
    }
    
    0 讨论(0)
  • 2020-11-21 04:56

    If you are supporting IE9+ the you can use the following. The same concept is incorporated in You Might Not Need jQuery.

    function addEventListener(el, eventName, handler) {
      if (el.addEventListener) {
        el.addEventListener(eventName, handler);
      } else {
        el.attachEvent('on' + eventName, function() {
          handler.call(el);
        });
      }
    }
    
    function triggerEvent(el, eventName, options) {
      var event;
      if (window.CustomEvent) {
        event = new CustomEvent(eventName, options);
      } else {
        event = document.createEvent('CustomEvent');
        event.initCustomEvent(eventName, true, true, options);
      }
      el.dispatchEvent(event);
    }
    
    // Add an event listener.
    addEventListener(document, 'customChangeEvent', function(e) {
      document.body.innerHTML = e.detail;
    });
    
    // Trigger the event.
    triggerEvent(document, 'customChangeEvent', {
      detail: 'Display on trigger...'
    });


    If you are already using jQuery, here is the jQuery version of the code above.

    $(function() {
      // Add an event listener.
      $(document).on('customChangeEvent', function(e, opts) {
        $('body').html(opts.detail);
      });
    
      // Trigger the event.
      $(document).trigger('customChangeEvent', {
        detail: 'Display on trigger...'
      });
    });
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>

    0 讨论(0)
  • 2020-11-21 04:57
    var btn = document.getElementById('btn-test');
    var event = new Event(null);
    
    event.initEvent('beforeinstallprompt', true, true);
    btn.addEventListener('beforeinstallprompt', null, false);
    btn.dispatchEvent(event);
    

    this will imediattely trigger an event 'beforeinstallprompt'

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

    I searched for firing click, mousedown and mouseup event on mouseover using JavaScript. I found an answer provided by Juan Mendes. For the answer click here.

    Click here is the live demo and below is the code:

    function fireEvent(node, eventName) {
        // Make sure we use the ownerDocument from the provided node to avoid cross-window problems
        var doc;
        if (node.ownerDocument) {
            doc = node.ownerDocument;
        } else if (node.nodeType == 9) {
            // the node may be the document itself, nodeType 9 = DOCUMENT_NODE
            doc = node;
        } else {
            throw new Error("Invalid node passed to fireEvent: " + node.id);
        }
    
        if (node.dispatchEvent) {
            // Gecko-style approach (now the standard) takes more work
            var eventClass = "";
    
            // Different events have different event classes.
            // If this switch statement can't map an eventName to an eventClass,
            // the event firing is going to fail.
            switch (eventName) {
            case "click": // Dispatching of 'click' appears to not work correctly in Safari. Use 'mousedown' or 'mouseup' instead.
            case "mousedown":
            case "mouseup":
                eventClass = "MouseEvents";
                break;
    
            case "focus":
            case "change":
            case "blur":
            case "select":
                eventClass = "HTMLEvents";
                break;
    
            default:
                throw "fireEvent: Couldn't find an event class for event '" + eventName + "'.";
                break;
            }
            var event = doc.createEvent(eventClass);
    
            var bubbles = eventName == "change" ? false : true;
            event.initEvent(eventName, bubbles, true); // All events created as bubbling and cancelable.
    
            event.synthetic = true; // allow detection of synthetic events
            // The second parameter says go ahead with the default action
            node.dispatchEvent(event, true);
        } else if (node.fireEvent) {
            // IE-old school style
            var event = doc.createEventObject();
            event.synthetic = true; // allow detection of synthetic events
            node.fireEvent("on" + eventName, event);
        }
    };
    
    0 讨论(0)
  • 2020-11-21 05:00

    You could use this function i compiled together.

    if (!Element.prototype.trigger)
      {
        Element.prototype.trigger = function(event)
        {
            var ev;
    
            try
            {
                if (this.dispatchEvent && CustomEvent)
                {
                    ev = new CustomEvent(event, {detail : event + ' fired!'});
                    this.dispatchEvent(ev);
                }
                else
                {
                    throw "CustomEvent Not supported";
                }
            }
            catch(e)
            {
                if (document.createEvent)
                {
                    ev = document.createEvent('HTMLEvents');
                    ev.initEvent(event, true, true);
    
                    this.dispatchEvent(event);
                }
                else
                {
                    ev = document.createEventObject();
                    ev.eventType = event;
                    this.fireEvent('on'+event.eventType, event);
                }
            }
        }
      }
    

    Trigger an event below:

    var dest = document.querySelector('#mapbox-directions-destination-input');
    dest.trigger('focus');
    

    Watch Event:

    dest.addEventListener('focus', function(e){
       console.log(e);
    });
    

    Hope this helps!

    0 讨论(0)
  • 2020-11-21 05:01
    function fireMouseEvent(obj, evtName) {
        if (obj.dispatchEvent) {
            //var event = new Event(evtName);
            var event = document.createEvent("MouseEvents");
            event.initMouseEvent(evtName, true, true, window,
                    0, 0, 0, 0, 0, false, false, false, false, 0, null);
            obj.dispatchEvent(event);
        } else if (obj.fireEvent) {
            event = document.createEventObject();
            event.button = 1;
            obj.fireEvent("on" + evtName, event);
            obj.fireEvent(evtName);
        } else {
            obj[evtName]();
        }
    }
    
    var obj = document.getElementById("......");
    fireMouseEvent(obj, "click");
    
    0 讨论(0)
提交回复
热议问题