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");
Related
I'm using Woocommerce (Wordpress) and utilizing the custom event listener defined by woocommerce called show_variation to listen for changes in the variation shown (when changed from viewing one variation of a product to another).
Question 1
The problem with this event listener is that it fires on page load, and I need it to only fire on changes (after page load). As I'm not sure whether this could load after the jQuery $(window).on('load', function(){... I'm reluctant to placing my faith entirely on the on(load) event. Also I would prefer it to only be fired .on('click').
Therefore my question is: is it possible to require a double event for the function to be fired? I'm thinking something like beneath (doesn't work though):
$(element).on('click + show_variation', function(){
alert("variation shown");
});
As of now I've "solved" this by doing wrapping the show_variation event listener inside a click event listener, but I'm afraid that this isn't a bulletproof solution:
$(container).on('click', function(){
$(element).on('show_variation', function(){
alert("variation shown");
});
});
However, using te last solution causes the show_variation event listener to bubble (adding multiple event listeners and firing multiple functions).
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.
My situation is that I am trying to trigger a single event using the jQuery .trigger() method. However the element I am triggering has multiple click event listeners.
Actually finding what these listeners are and what they trigger from the source code is probably not viable as its included in the sites main JS file and its all minified and pretty much unreadable.
At the moment I know that the element when clicked performs some kind of ajax call and loads more data into the DOM of the page (which is what i want to trigger), however it also displays an overlay (which is what I want to suppress temporarily).
As its just an overlay there are workaround I can make; using a display:none on it straight after click etc. However it would be much more elegant if i could somehow suppress all click events on this element except the desired event.
Any ideas if this is actually possible? And if so how I would go about it?
You need to register your own event at the top of the event chain. And cancel the event chain in your event. Here is a solution with writing a custom jquery extention.
$.fn.bindFirst = function (which, handler) {
var $elm = $(this);
$elm.unbind(which, handler);
$elm.bind(which, handler);
var events = $._data($elm[0]).events;
var registered = events[which];
registered.unshift(registered.pop());
events[which] = registered;
}
$("#elm").bindFirst("click", function(e) {
// edit: seems like preventing event does not work
// But your event triggers first anyway.
e.preventDefault();
e.stopPropagation();
});
Reference:
https://gist.github.com/infostreams/6540654
EDIT:
https://jsfiddle.net/8nb9obc0/2/
I made a jsFiddle and it seems like event preventing does not work in this example. There might be another solution.
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')
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/