simonzack
simonzack

Reputation: 20938

Jquery dispatchEvent wrapper method

Is there a wrapper method or some library for dispatchEvent in jquery? I've been looking for this on stackoverflow, but the closest method I've found is jquery's trigger(), which appears to only trigger jquery event listeners. Of course I could just use dispatchEvent myself, but I want to use jquery to make my code easier to read.

I'm writing a greasemonkey script, where I want to fire an event to some anonymous event listener. The page itself is not written in jquery.

Here's a jsfiddle link to explain what I'm trying to accomplish: https://jsfiddle.net/Zx3CA/

js:

function log(s){
    document.getElementById('log').innerHTML+=s+'<br/>';
}

$(function(){
    //code on the page, which shouldn't be changed
    //start
    document.getElementById('link').addEventListener('click',function(){
        log('click detected');
    },false);
    //end
    
    $('#triggerClickJQuery').on('click',function(){
        $('#link').trigger('click');
    });
    
    $('#triggerClickJS').on('click',function(){
        var event=document.createEvent('MouseEvents');
        event.initMouseEvent('click',true,true,null,-1,-1,-1,-1,0,true,false,false,true,0,null);
        $('#link').get(0).dispatchEvent(event);
    });
});

html:

<body>

<a id="link" href="javascript:void(0);">Link</a><br/>
<a id="triggerClickJQuery" href="javascript:void(0);">Trigger Click JQuery</a><br/>
<a id="triggerClickJS" href="javascript:void(0);">Trigger Click JavaScript</a><br/>

<div id="log"></div>

</body>

Thanks in advance.

Upvotes: 8

Views: 6696

Answers (1)

user566245
user566245

Reputation: 4227

The implementation of trigger in jQuery (upto 1.10.1) for custom events doesn't fire a native event and therefore you wont be able to listen for it via addEventListener or a different version of jQuery loaded on the same page.

This bug with all of its use-cases is well documented here: http://bugs.jquery.com/ticket/11047

As a solution you can use this plugin, which checks if the browser supports firing custom native events and uses it when available.

https://github.com/sandeep45/betterTrigger

Upvotes: 12

Related Questions