How to trigger event in JavaScript?

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

提交回复
热议问题