I am using a library that when complete will trigger an event via $(document).trigger('playlistDone');. I am listening to this trigger but I am not getting the alert() I am expecting.
$(document).bind('playlistDone', function() {
alert('done');
});
What am I doing wrong?
First off, as of jQuery 1.7 the preferred method for attaching events is on, not bind (see http://api.jquery.com/on/).
Second, your basic syntax looks ok, but it's important to understand you're dealing with custom events, not browser events. This means that your library must be using jQuery to trigger its event, or else jQuery won't detect it when it happens.
Use .on(). From jQuery documentation :
The .on() method attaches event handlers to the currently selected set
of elements in the jQuery object. As of jQuery 1.7, the .on() method
provides all functionality required for attaching event handlers.
Try something like that:
$(document).on('playlistDone', function( a ) {
alert( a );
});
and
var data = 'Done';
$(document).trigger('playlistDone', data );
Related
What are the advantages of using jQuery's
$(window).blur(function() { ... })
to attach an event handler versus setting it directly with
window.onblur = function() { ... }
It seems that the latter is less robust because it only supports one blur handler, and when used with other packages, other code might override the window.blur value with another function. However, couldn't this also happen with the jQuery implementation too, which presumably uses window.blur as its underlying implementation?
EDIT: Several people have also mentioned the window.addEventListener alternative, which can be used to add an 'onblur' event apart from the methods above.
$(window).blur(function() { ... })
Lets you add one or more event handlers.
window.onblur = function() { ... }
Lets you only have one event handler handling the blur event.
The former uses the jQuery's own event handle mechanism. The call to .blur() will delegate to jQuery.fn.on() which in turn will delegate to jQuery.event.add. This add() method will create it's own handler for the given event type and tell addEventListener() to call this handler whenever a event of given type is fired. So basically jQuery has it's own way of event handling which relies on addEventListener() to execute properly.
The latter is just an attribute which can only contain one value so queueing event handlers is impossible.
I wrote a little demonstration to prove this point: http://jsfiddle.net/GnNZm/1/
With the jQuery method, you can attach multiple event handlers. By setting window.onblur, you can only have a single handler.
Pure JavaScript also has this: window.addEventListener(). In fact, i'm sure jQuery uses this internally. (Yes they do.)
(EDIT)
The window.onblur property is basically a shortcut for setting a single handler. Using addEventListener() (or the jQuery wrapper) basically creates a list of event handlers, which all get fired when the event happens. I haven't tested, but i think you can even use the two together. Because it's a list, not a single value, multiple handlers shouldn't interfere with each other. They can also be removed separately or all at once.
jQuery's event handlers, using on(), also let you namespace your handlers, to prevent clashes if a plugin removes its handlers. Pure JS doesn't seem to have this easily.
For jquery blur
The blur event does not bubble in Internet Explorer. Therefore,
scripts that rely on event delegation with the blur event will not
work consistently across browsers. As of version 1.4.2, however,
jQuery works around this limitation by mapping blur to the focusout
event in its event delegation methods, .live() and .delegate().
taken from jquery doc https://api.jquery.com/blur/
Also jquery allows you bind multiple event handlers
When you attach an event there is the possibility of overwriting an event already attached to an event handler. This used to happen a lot with window.onload() where different scripts overwrote each others event handlers.
eg:
//lightbox.js
window.onload = function() { /* do lightbox stuff */ }
//carousel.js
window.onload = function() { /* do carousel stuff */ }
So the common practice used to be something like this:
var existing_event_handlers = window.onload;
window.onload = function(){
//my event code
alert('onready fired');
//call other event handlers after
existing_event_handlers();
}
Using window.onblur = function() { ... } still has an advantage because you can specifically dictate if you want your event fired before or after other attached events.
Like many other answers already pointed out jQuery abstracts you from most browser differences. Version before IE9 used attachEvent() rather than addEventListener().
I have one anchor element in my page
Click
I know in jQuery we have so many ways of binding events to element like (bind, live, delegate, on).
FYI:
http://blog.tivix.com/2012/06/29/jquery-event-binding-methods/
Currently using jquery1.8.3.min.js. I want to know which one is standard and efficient event registration model in jQuery?
Currently I am doing it like this:
$("#page").click(function(){
................................
});
Can I change to bind like below code:
$("#page").bind("click",clickFunc);
function clickFunc()
{
..........
}
Which one is best practice to register the event in jQuery 1.8 ?
The best way is the way one can understand what's written and the one that works.
The smart way is to use what's suggested to use, in this case the .on() method:
The .on() method attaches event handlers to the currently selected set of elements in the jQuery object. As of jQuery 1.7, the .on() method provides all functionality required for attaching event handlers. For help in converting from older jQuery event methods, see .bind(), .delegate(), and .live(). To remove events bound with .on(), see .off(). To attach an event that runs only once and then removes itself, see .one()
The how-to way depends if you need to delegate your event/s to dynamically generated elements or not.
$('.child').on( 'click', function() { /* ... */ });
$('#parent').on( 'click', ".dyn-gen-child", function() { /* ... */ });
.on is the standard method:
$("#page").on("click", function() {
.......
});
If the p element is generated dynamically, you'll have to do:
$(document).on("click", "#page", function() {
.......
});
Actually, after jQuery 1.7, on is the preferred way to bind events rather than bind. So I prefer on API.
And then:
click(function(){})
is just the shortcut of
on('click',function(){})
Internally, they are actually the same -- when the on param is event, handler, but on is more general because it can do more than simple onClick(example:event delegation) see:link
so I recommend on
I want to trigger this jquery function by using trigger method of JQuery. How can I do that ? Actually I dont even know the trigger method is suitable for user defined functions.
$('a.pop').click(function() {alert('testing'); }
this is not working
$('a').trigger(testtt);
var testtt = function(){ alert('aaa');}
Very similar to the way you install the event handler:
$('a.pop').click();
If you have the name of the event you want to trigger as a string, you can also do it this way:
$('a.pop').trigger('click');
This is also the solution to use if you want to pass crafted data to the event handler -- trigger also accepts a second parameter.
You can trigger a click event on the element by simply running
$('a.pop').click()
$('a.pop').click(), or if you're triggering some dynamic method, or custom event:
$('a.pop').trigger(eventName), e.g: $('a.pop').trigger('click');
Reading from jQuery API, the following should work.
$('a.pop').trigger('click');
.trigger() is used to trigger event handlers (custom or built-in'). Since you bound your function to the "click" handler, you can use trigger like so to call it:
$('a.pop').trigger('click');
jQuery's event binding methods can also be called without parameters to trigger them, which means you can also do this:
$('a.pop').click();
I'm currently upgrading my application to use jQuery 1.6.1 (previously using 1.4.4) and found that now the .click() event automatically triggers a .change() event as well.
I created a simple example here: http://jsfiddle.net/wDKPN/
Notice if you include 1.4.4 the .change() function will not fire when the .click() event is triggered. But when switching to 1.6, the .change() event is fired when .click() is triggered.
Two questions:
Is this a bug? It seems that programmatically triggering .click() shouldn't also fire other events (for example, it would seem wrong to also automatically fire .blur() and .focus(), to help "mimic" a user's click).
What is the proper way for me to bind a change() event and then trigger both a click() and change() event for that element? Do I simply call .click(), and rely on the fact that .change() will also fire?
$('#myelement').change(function() {
// do some stuff
});
$('#myelement').click(); // both click and change will fire, yay!
In my old code I'm using this pattern to initialize some checkboxes (and their checked states and values) after an ajax call:
$('#myelement').change(function() {
// do some stuff including ajax work
}).click().change();
But in 1.6.1 my logic fires twice (once for .click() and once for .change()). Can I rely on just removing the .change() trigger and hope that jQuery continues to behave this way in future versions?
Best way to do this is:
$('#myelement').bind('initCheckboxes change', function() {
// do some stuff including ajax work
}).trigger('initCheckboxes');
To do your initialization stuff you just bind to it a custom event, which you trigger it the first time the page loads. This, no one will take away from you on any versions.
Whereas change event, I believe, will continue to be there on all versions, because it has been for so long, and it just works nicely that way.
In the end, this is a happy ending story, because the custom event initCheckboxes will fire just once on page load and change event will always listen and fire on change state.
I would say this was a bug in jQuery 1.4.4. Removing the jQuery event handlers and using standard addEventListener produces the same result as jquery 1.6.1.
http://jsfiddle.net/jruddell/wDKPN/26/
window.count = 0;
document.getElementById('mycheckbox').addEventListener('change', function() {
window.count++;
jQuery('#output').append('I fired: ' + window.count + ' times<br />');
});
document.getElementById('mycheckbox').click();
Also I would use triggerHandler to specifically invoke a jQuery event handler. If you want the event model to determine which handlers to call, then use click, change etc.
Forget about the click event for checkboxes. The change event handles everything.
$('#myelement').change(function() {
// do some stuff
});
$('#myelement').trigger('change');
See for yourself: http://jsfiddle.net/zupa/UcwdT/
(This demo is set to jQuery 1.8 but works in 1.6 as well.)
I think you can make it work for both jQuery 1.4.4 and 1.6 implementations by putting change() within click handler and then triggering the click.
$('.myelement').click(function(){
$('.myelement').change();
alert($(this).val());
});
$('.myelement').trigger('click');
Have a look there for simple example.
i have a code that bind's on click action on page load, it is a link. When i clicking it, it send ajax request and replace content in some div with jquery append() function. This new content has a links and i need to bind some action for them, but i could't.. bind did't work i think, because jquery append doesn't update DOM tree. How could i get a late binding?
There are 3 functions that can do this:
$(selector).live(events, data, handler); - jQuery 1.3+ - version deprecated: 1.7, removed: 1.9 (reference)
$(document).delegate(selector, events, data, handler); - jQuery 1.4.3+ - As of jQuery 1.7, .delegate() has been superseded by the .on() method. (reference)
$(document).on(events, selector, data, handler); - jQuery 1.7+ - preferred (reference)
It's generally adviced to use on() and it's use is simple and probably preferred way.
The first selector must exist when calling the function and may not be deleted or the event will be gone too (this can be document).
The first parameter is the event (e.g. "click")
The second parameter is the selector of which you want to bind the event on.
Then finally you can add some custom data and a function to the event.
Here's some sample code:
// Make sure the DOM is ready
$(function() {
// Bind the click event to the function
$(document).on("click", "a.class", function(event) {
// Put your code here.
});
});
Late binding is now available by utilizing jQuery's live() event:
$('a.my-links-class').live('click', function() {
// do your link action here
});
Method .live in JQuery 1.9 is deprecated.So now u can do like this:
$("body").on("click", ".classname", function() { ... })
the .live() event was deprecated from verions 1.9 up.
For anyone using later version of Jquery they can use the .on() event, it works pretty much in the same way.
You need to use jQuery's live function, which will bind an event to all elements that match a selector, no matter when they were created.
You can use jQuery 1.3+'s $().live(event, function) function. $("a").live("click", myClickFunc) will bind myClickFunc just like $("a").click(myClickFunc) or $("a").bind("click", myClickFunc), but the events will be bound "live", so elements that are added to the DOM after that function call will also be bound.
You can remove live-bound events with $().die().
For more information on $().live, see the documentation for it.
Another option would be to have a function to bind the elements given a certain context (using the $ selector function's rarely-used second parameter):
function myBindEvents(context) {
$("a", context).click(myClickFunc);
}
and call that whenever you update an element with AJAX:
$("<div>").load("...", "...", function(){myBindEvents(this);});
Hope this helps. :)
In my case I am using js library in that I have element variable and code was like
$(element).click(function(){
//some action
});
but that is not working with my late binding element.
So I finally use core js click event
element.addEventListener('click', function() {
//My some action
}, false);