YUI3: How would I trigger an event? - javascript

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/

Related

Jquery trigger works only for one event specified by addEventListener at a time

I'm building a library without depending on Jquery in order to better my javascript knowledge. However in writing tests for the library I'm using some Jquery methods.
I have a test that triggers events listeners added using the native EventTarget.addEventListener method using Jquery's .trigger method.
var elem = document.getElementById('square');
elem.addEventListener('click', function () {
alert('click');
});
elem.addEventListener('mouseover', function () {
alert('mouseover');
});
$(elem).trigger('click');
$(elem).trigger('mouseover');
When I trigger two different events on the same element, only one handler fires.
This can be observed in this JSFiddle
Can someone explain why this happens and how to fix it?
If you are using addEventListener, you can't use jQuery's trigger method. (It will work for some events like click, but not for everyone, like mouseover, as you noticed). This is also explained in this question.
You have two options. Either you use jQuery's on event like this:
$(elem).on('mouseover', function () {
alert('mouseover');
});
Or the other is to trigger the event without using jQuery. You can check this question to do that.

Simulate clicking a button

If I have an existing click event associated with a button, can I use code to simulate that button being pressed so the code in the click event will run? I'm asking because I want there to be certain times where the user does not have to press the button for code to be executed. I would like to press the button automatically for them in certain instances if that makes any sense.
As simple as this,
$(function() {
$('#button').trigger('click');
});
var button = document.getElementById('yourButtonIdHere');
button.click();
This will fire a click event in the button
You can trigger a click event on an element by calling the .click() function on the element. By passing no value to the function the click event will fire, as opposed to setting up a listener for the click event.
If the button has an id of "form-btn", here's what that would like:
<button id="form-btn">Submit</button>
<script type="text/javascript">
//Setup the click event
$('#form-btn').on('click', function (e) {
alert('clicked!');
});
//Call the click event
$('#form-btn').click();
</script>
This should work fine, although I usually try to use a named function when setting up my event handlers, instead of anonymous functions. By doing so, rather than triggering the event I can call the function directly.
Note that in my experience, older browsers (IE6, IE7) sometimes limit what code-triggered events can do as a safety precaution for the user.
Here's documentation on the .click() function: http://www.w3schools.com/jquery/event_click.asp
Edit 1
I forgot that jQuery also has the .trigger() function, as used in choz's answer. That will also the job quite nicely as an alternative to .click(). What's nice about .trigger() is that it can trigger standard events as well as custom events, and also allow you to pass more data in your event.
Just make a function and run the function from within the button.
Three Choices:
You can call the click event handling function directly when appropriate:
if(timeIsRightForClick){
yourClickHandler();
}
You can simulate a button click by calling the .click() method of the button.
$("#ButtonID").click()
https://api.jquery.com/click/
Same as #2, but using jQuery's trigger() function, which can be used on standard events and custom ones:
$("#ButtonID").trigger("click");
http://api.jquery.com/trigger/
Choices #2 and #3 are usually better because they will cause the event handling function to receive a reference to the click event in case it needs to use that object. Choice #1 doesn't cause an actual click event (just runs the code you tell it to) and so no event object is created or passed to the event handler.

Bind click event to jquery.appear

I'm using the plugin Jquery.appear for a project I'm working with. It works great and it's issue free, but I'm curious to know if I can bind a click event to it. Basically what I'm after is when I scroll to a certain div down the page, an event fires, easy. However, I also would like to make it so I can have a 'click' event fire off as well but without the user actually clicking. So I was thinking using bind would make this possible. I'll include what I have below.
$(function() {
var $appeared = $('#boost-que');
$('#boost-que').appear();
$(document.body).one('appear', '#boost-que', function(e, $affected) {
function testScroll() {
alert('works');
}
$(document.body).bind('click', testScroll);
$appeared.empty();
});
});
This works, but I have to physically click to make the click event fire. Is there a way to bind the click event so it will fire by itself? Any input is always appreciated.
You can programmatically click it by calling click() after binding:
$(document.body).bind('click', testScroll).click();
or:
$(document.body).bind('click', testScroll).trigger("click");

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.
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

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

Categories