Why jQuery live() does not work? - javascript

I have the following code which work fine:
$('.ui-selectmenu-menu a').click(function() { alert('OK'); });
However, if I replace it with:
$('.ui-selectmenu-menu a').live('click', function() { alert('OK'); });
it does not work.
What could be the reason for that ?
(In my case, $('.ui-selectmenu-menu a') elements could be removed and added again during the run.)

If the class changes e.g. the parent doesn't have class="ui-selectmenu-menu then the selector would no longer match, make sure this isn't happening after whatever events you have.
Unlike binding directly to the element, the selector no longer matching will stop a .live() handler from firing for that element's events.

Nick's answer makes sense. But also, check that you have jquery version 1.3 or greater.
.live() was added in jquery version 1.3.

Related

.bind() .live() not working in Safari or Chrome, but works in Firefox

I am very new to this. Can someone help point me in the right direction?
I've got my website mostly working the way I want in Firefox, but now that I try test it in Safari or Chrome, it doesn't work. I'm sure there will be many more problems later, but the first issue is that I am dealing with is my main nav buttons are not working. The click handlers and mouseleave and mouseenter are not working.
Is there something wrong with this code or could it be a problem somewhere else?
function onLoad () {
var $list= $('#mainNavList');
showMainMenu(); //make menus appear
specifyScrollingElement('#mainNavList');
specifyScrollingElement('#lowerNav');
$list.find('.linkInactive').live('click', onMainNavMenuClick);
$('.albumLink').parent().bind('mouseenter',function(){
$(this).css({'background-color': '#fff'});
});
$('.albumLink').parent().bind('mouseleave',function(){
if ($(this).hasClass('current')==false){
$(this).css({'background-color': 'rgba(233,229,194,.9)'});
};
});
$('.textLink').parent().bind('mouseenter',function(){
$(this).css({'background-color': 'rgba(65,65,65,.8)'});
});
$('.textLink').parent().bind('mouseleave',function(){
if (portfoliosActive ==false && $(this).children().hasClass('portfolioButton')==true ){
$(this).css({'background-color': 'transparent'});
};
if (portfoliosActive ==true && $(this).children().hasClass('homeButton')==true){
$(this).css({'background-color': 'transparent'});
};
});
$list.find('.linkActive').live('click',function(){
var $this = $(this);
$this.addClass('linkInactive').removeClass('linkActive');
hideThumbs($list);
});
thumbnailActions('#mainNavList');
thumbnailActions('#lowerNav');
initUpperNavActions();
}
Use 'on' instead of 'bind' and 'live'... that should save you a world of pain later.
Those methods are deprecated as of jquery 1.7..
See the follow link for more info: http://api.jquery.com/bind/
As of jQuery 1.7, the .on() method is the preferred method for attaching
event handlers to a document. For earlier versions, the .bind() method is
used for attaching an event handler directly to elements. Handlers are
attached to the currently selected elements in the jQuery object, so those
elements must exist at the point the call to .bind() occurs. For more flexible
event binding, see the discussion of event delegation in .on() or .delegate().
and also: http://api.jquery.com/live/
As of jQuery 1.7, the .live() method is deprecated. Use .on() to attach
event handlers. Users of older versions of jQuery should use .delegate()
in preference to .live().
And example of using 'on' for your code would be:
$('.albumLink').parent().on('mouseenter',function(){
$(this).css({'background-color': '#fff'});
});
You should use .on() it binds and persists. I use it in chrome with no issues.
$(".albumLink").on('click', function () {
$(this).css({'background-color': 'rgba(65,65,65,.8)'});
});
http://api.jquery.com/on/
if you are using an older jQuery you might have to use delegate()
http://api.jquery.com/delegate/
** NOTE: delegate switches the parameter order. In later Jquery (1.7) .delegate() is just an alias for .on() anyway
hth
I wasn't able to get on or delegate to work. I think I am still confused about how to use jquery.
But I figured out what the problem was with my click and mouseenter and mouseleave not working. I discovered an extra "</div>" in the code so I think there was an invisible div blocking my nav buttons. After I deleted it, the buttons all suddenly work in Safari and Chrome! Thanks for your time!

How to list events which were bind by jQuery?

How to list events which were bind by jQuery for an element? I tried the methods from this question and none worked.
jsFiddle example
The code you linked to does work, it's just that because you used live() (which is a deprecated function from version 1.7 on), the handler is bound to the top level element, the document, and it uses event bubbling to figure out the original element and see if it matches your selector.
Because you tried to call the $.eventReport() for a specific selector, rather than document, nothing was returned.
If you change live to on, you will see that the alert does show something (jsFiddle). Alternatively, if you omit the selector to $.eventReport() altogether, you will also see that a click event is bound (jsFiddle).
Example for the former:
$(function() {
$('#firstname').on("click", function(e) {
alert('clicked');
});
alert($.eventReport('#firstname'));
});​

jQuery on() with ajaxed content

I am trying to bind click handlers to incoming ajaxed content. I used to use 'live'
$('#div').live('click', function(event) {
alert('I got clicked, Live style');
});
But now as my site is getting more complicated, I am realizing how crazy things can get using live and having everything bubble to the top of the DOM. Which is not ideal.
So I started using on(),
$('#div').on('click', function(event) {
alert('I got clicked, On style');
});
But I miss the fact that using live() I could just initialize the click handlers once and be done with it instead of reinitialize them every time new content is loaded. Is there a best of both worlds?
Is there a better way to "reload" click handlers to recognize new ajax content aside from creating the handlers in the ajax callback function? To me that seems highly suspect. Whats the appropriate way to do this?
As of jQuery 1.7 the following .on() event binding is equivalent to the deprecated live:
$(document).on('click', '#div', function(event) {
alert('I got clicked, On style');
});
You can also bind the event to some fixed element further down the DOM which doesn't get re-generated, this functionality would be the same as .delegate():
$('#parentofdiv').on('click', '#div', function(event) {
alert('I got clicked, On style');
});
It is advisable to use the second form to narrow down the scope of the event binding as much as possible to make it easier to maintain.
Edit: For the record, what you originally did in your post would be the preferred replacement for your .bind() calls in your code.
Have you looked at using .delegate? http://api.jquery.com/delegate/
jQuery's on() method can be used to attach various events to already existing items as well as items added by ajax calls to the DOM in the future:
$(document).on("click", ".ajax-added-content", function(event) {
alert('I got clicked, On style');
});
It is possible to do what you want with
.on()
and it is actually the recommended method.
.live()
is deprecated as of jquery 1.7.
You can attach your event to the body and use this overload of "on" to get the functionality you desire. Check the next to last example in jquery's doco of .on
$("body").on("click", "#div", function(){
alert('I got clicked, On style');
});

Use JS that is already loaded, on HTML loaded via jQuery's load() function?

Not sure if this is posible or not, but I'm trying to use JavaScript that I loaded via a script tag when the page was initially requested on dynamic HTML that was loaded via jQuery's load() function.
Example: http://jsfiddle.net/3MR43/
As you can see in the example, after clicking a link in the pop up box, the link goes. The problem is that the link was suppose to be stopped, and you were suppose to see an alert.
However, if I paste the HTML that I am loading via jQuery, it works, so the code is fine.
Description
You need jQuery .live() or .on() method to bind events to dynamically created html.
Choose .live() or .on() depending on the version of jQuery you are using.
.live() Available since jQuery 1.3. Attach an event handler for all elements which match the current selector, now and in the future.
.on() Available since jQuery 1.7. Attach an event handler function for one or more events to the selected elements.
Check out my sample and this jsFiddle Demonstration
Sample
... for jQuery.live()
$('.lang').live("click", function(e) {
e.preventDefault();
alert('Testing..');
});
... for jQuery.on()
$('.lang').on("click", function(e) {
e.preventDefault();
alert('Testing..');
});
More Information
jsFiddle Demonstration
jQuery.live()
jQuery.on()
The problem is your .click will do it for only elements that exist at that time. If you want to do it for all potential future elements that that selector will match, you want to use on() (delgate() or live() with older versions of jQuery).
The $('.lang').click() event must be registered after the element is created!
You need a callback on the load function to register this.
You need to use live to attach handlers to elements that are loaded dynamically.
Try this, it will solve your problem.
$('.lang').live('click',function(e) {
e.preventDefault();
alert('Testing..');
});
You have to use on function for dynamicly loaded elements:
$('.open_lang').click(function(e) {
e.preventDefault();
$('#popup').load('http://skins.thehabbos.org/pop_up/language.php').css('display', 'block');
});
$('body').on('click', '.lang', function(e) {
e.preventDefault();
alert('Testing..');
});
(live and delegate are deprecated in JQuery 1.7+ which is the version of your JSFiddle)
Fixed JSFiddle

Why jQuery on click event not getting triggered?

I have an group of checkboxes with id's starting with somename and I want catch the click event of these checkboxes. Previously I have done this through jQuery. i.e.:
$("input[id^='somename']").click(function(){
// my code follows here
})
but this is not working this time around. Why?
P.S. The element is created via JavaScript after the page is fully loaded after making some ajax request. I don't know if this may be the problem?
just use live if elements are created after the page is loaded.
$("input[id^='somename']").live('click', function(){ // my code follows here })
P.S : Your search selector is "somename" but you search it on the attribute ID, are you sure that you don't want :
$("input[name^='somename']").live('click', function(){ // my code follows here })
instead?
This indeed could be the problem. Replace .click with .live()
$("input[id^='somename']").live('click', function(){ // my code follows here })
and you should be fine.
Since a call to .click is just a shortcut for .bind('click', fnc), this will not work if the element is not in the DOM when calling this. Even better than using .live() would be to use .delegate(). Have a read:
.live(), .delegate()
Using the standard binding functions only works on elements that exist at the time of the bind. You need to use something called event delegation, where elements further up the DOM tree are notified of events on descendant elements. The best way to do this is with .delegate():
$('#containingElement').delegate("input[id^='somename']", 'click', function(){
// your code here
});
This assumes that you have an element #containingElement that contains all the elements that you want to capture the events on.
NB that other answers recomment live. live and delegate use the same backend code, but for various reasons delegate is more efficient.
I believe that because you want this applied to dynamically created elements in the DOM you are going to have to use the the jQuery .live() method:
$("input[id^='somename']").live('click', function(e) {
// Your code
});
Instead of .click() try .change() event.

Categories

Resources