Jquery dispatchEvent wrapper method - javascript

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.

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

Related

Manually click a child link (and navigate) when clicking parent [duplicate]

Recently I found jQuery cannot trigger the native click event on an anchor tag when I'm clicking on other elements, the example below won't work:
html
<a class="js-a1" href="new.html" target="_blank">this is a link</a>
<a class="js-a2" href="another.html" target="_blank">this is another link</a>
javascript
$('.js-a1').click(function () {
$('.js-a2').click();
return false;
});
And here is the jsfiddle - 1. Click on the first link won't trigger native click on the second one.
After some searches, I found a solution and an explanation.
Solution
Use the native DOM element.
$('.js-a1').click(function () {
$('.js-a2').get(0).click();
return false;
});
And here is the jsfiddle - 2.
Explanation
I found a post on Learn jQuery: Triggering Event Handlers. It told me:
The .trigger() function cannot be used to mimic native browser events, such as clicking on a file input box or an anchor tag. This is because, there is no event handler attached using jQuery's event system that corresponds to these events.
Question
So here comes my question:
How to understand 'there is no event handler attached using jQuery's event system that corresponds to these events'?
Why is there not such corresponding event handler?
EDIT
I update my jsfiddles, it seems there's and error on the class name.
there is no event handler attached using jQuery's event system that corresponds to these events
This means, at this point of the learning material, no jQuery event handlers has been attached to these elements using .click(function() {} or .bind('click', function () {}), etc.
The no-argument .click() is used to trigger (.trigger('click')) a "click" event from jQuery's perspective, which will execute all "click" event handlers registered by jQuery using .click, .bind, .on, etc. This pseudo event won't be sent to the browser.
.trigger()
Execute all handlers and behaviors attached to the matched elements for the given event type.
Check the updated jsFiddle example, click on the two links to see the difference. Hope it helps.
First of all you need to prevent the default behaviour of link
$('.js-a1').click(function (e) {
e.preventDefault();
$('.js-a2').get(0).click();
return false;
});
And to trigger the click event you can also use .trigger('click') better way
And the event handler is used like this:
$(document).on('click', '.js-a1',function(){//code in here});
// here now .js-a1 is event handler
i think you forgot to read documentation.
Document says :
// Triggering a native browser event using the simulate plugin
$( ".js-a2" ).simulate( "click" );
Old question, but here's a nifty and simple solution:
You can basically "register" a native JS event with jQuery by assigning the DOM element's onEvent handler to be the native event. Ideally, we would check first to ensure the onEvent handler has not already been set.
For example, 'register' the native JS click event so it will be triggered by jQuery:
$('.js-a1').click(function (e) {
$('.js-a2').click();
e.preventDefault();
});
var trigger_element = $('.js-a2')[0]; // native DOM element
if (!trigger_element.onclick) {
trigger_element.onclick = trigger_element.click;
}
Here is a fiddle: http://jsfiddle.net/f9vkd/162/
You have to use $("selector").trigger('click')

YUI3: How would I trigger an event?

Suppose I have a click event on a link/button/etc.
var myButton = Y.one('.button');
myButton.on('click', function() {
// code
});
There is something else happening on the page that I want to trigger a click event on this button. How would I do this?
I saw YUI3's fire() method, but it looked like that was designed for custom events. If I am supposed to use fire(), then will myButton.fire('click') work?
(I'm looking for the equivalent of jQuery's .trigger() method, which works on DOM events or custom events.)
If you are looking for equivalent of trigger in yui3 you can try using the 'simulate'
Y.one('button selector').simulate('click');
For the above statement to work you will need to add "node-event-simulate" roll up in the use method.
Do you really need to trigger the click event on the button? Take the HTML below
<button id="myButton">Click Me</button>
<br>
Click Me
You can make use of the custom events to put the real logic somewhere central.
YUI().use("node","event",function(Y){
Y.one("#myButton").on("click",function(){Y.fire("custom:doThing")});
Y.all("a").on("click",function(){Y.fire("custom:doThing")});
Y.on("custom:doThing",function(){console.log("Do my thing, regardless of event source")})
});
Fiddle: http://jsfiddle.net/WZZmR/

jQuery click event not triggering button action

I am using jQuery and I have loaded a bunch of JavaScript for a web page which works as expected. However when I try to add the following code to trigger a button click, the button is not activated:
$(document).ready(function(){
$('.add_link').click();
});
I am wondering what I am doing wrong? I have this bit of code in a separate file that gets loaded after all the other JavaScript files are loaded. Any hints?
$('.add_link').click();
Maybe the button is not found, because it does not have the specified class. Look for typos or maybe you just forgot to set the class for the button?
What should happen, when you click the button?
What is the html code for this?
I have found the answer after playing around some more. Since I am using Drupal, I need to use a closure to make sure it works correctly. The correct code should be:
jQuery(document).ready(function($){
$('.add_link').click();
});
It is always the small things that trip you up. Thanks for all the responses.
HTML:
<button class="add_link">Click ME</button>
Javascript:
$(document).ready(function(){
$('.add_link').click(function(event){
//I'm the event handler
console.log(event);
alert(".add_link clicked!!!");
});
});
Other examples:
$(document).ready(function(){
//Named function
function myHandle(event){
//I'm the event handler
console.log(event);
alert(".add_link clicked!!!");
}
//adding event with event alias
$(".add_link").click(myHandle);
//adding event with jQuery.on
$(".add_link").on("click", myHandle);
//adding event with jQuery.on and delegation
$("body").on("click", ".add_link", myHandle);
});
I use jQuery.on because syntax of delegation and simple event handling is almost the same. jQuery.on is newer then jQuery.bind, jQuery.live and jQuery.delegate too.
jsFiddle

Why JQuery doesn't trigger added eventlistener?

I have recognized, that eventhandler added with addEventListener where not influenced by
$.trigger. The special reason for that question is, that I have several self created html elements which implements some logic without using external libraries (only pure js).
Now in my main project I want to use these controls and further there I have external libaries like jQuery.
Now for example I want to trigger the change event (remember...events are added with element.addEventListener("event", function)) with $(element).trigger("change").
Result: nothing happened
The event only is triggered, when i use code like this:
event = document.createEvent("HTMLEvents");
event.initEvent("change", true, true);
event.eventName = 'change';
element.dispatchEvent(event);
On the other side...eventhandler added with jQuery, where also triggered by a custom created event.
Now the magic question: Why??
You can find a little example in the following jsfiddle. http://jsfiddle.net/UYyXv/3/
I have got an explanation from the jquery forums.
jQuery events are a level higher than the native events. Trigger fakes
a jQuery event. If you want to fake a native event you need to call it
as you wrote in the question.
Simple answer, don’t use native events.
JΛ̊KE
why don't you just try
$(SELECTOR).change(function(e){
e.preventDefault();
//***DO STUFF HERE***
})

Focusin using live not working -jQuery

I am trying to attach a focusin event on a future element using jquery 1.5.2. Just to clarify,this has also been attempted using jQuery 1.7.2 with the same issue.
The event is not firing as i expected it to. Yet a similar click event works correctly using .live
I've put together an example here for you to take a look at my code. Hopefully this will not been a simple issue (although it always seems to be!).
Link to jsfiddle
This is my focusin event i am trying to attach
$(".active").live("focusin", function() {
$(this).text("focusin using live");
});
I believe i have found some related questions, but im unable to fix my code using them. I would prefer an explanation over a "here is your code corrected answer".
If you think i need to add more information to my question please leave a comment.
Related
jQuery focusin and focusout live events are not firing
Why the "focusin" event handler isn't called?
You need to focus the element if you expect the focusin event to trigger. The fact that you are applying a DOM element the .active class doesn't mean that you are focusing it.
$('.active').live('focusin', function() {
$(this).text('focusin using live');
});
$('.active').focus();
​
Here's a demo.
Another thing you will notice is that .live() supports the focusin event starting from jQuery 1.7.1. Obviously in this version of jQuery, .live() is deprecated and you should use .on():
$(document).on('focusin', '.active', function() {
$(this).text('focusin using on');
});
$('.active').focus();
​

Categories