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.
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…