Wedge

Public area => The Pub => Off-topic => Topic started by: MultiformeIngegno on February 3rd, 2013, 03:30 PM

Title: jQuery: .on() instead of .live()
Post by: MultiformeIngegno on February 3rd, 2013, 03:30 PM
This is my .live() script I need to update because it's deprecated:
http://jsfiddle.net/wtz5f/1/

This is my tentative to use .on() for the same behavior (but nothing happens..):
http://jsfiddle.net/PjQ3N/1/

What's wrong with the latter example? :)
Title: Re: jQuery: .on() instead of .live()
Post by: Dragooon on February 3rd, 2013, 03:49 PM
Two things

1) You're using the function wrong, it should be (similarly for the mouseleave function)
Code: [Select]
jQuery(document.body).on("mouseenter", "#ultimecomunicazioni", function() {
        jQuery('<span id="ultimecomunicazioni_appear" style="font-weight:normal;margin-left:5px">(<a style="color:grey" href="//google.it">tutte</a>)</span>').appendTo(jQuery(this));
 });

2) You're delegating events to an ID, that's pointless since you're only supposed to have one element in the DOM with the same ID. You might as well use bind after document.load
Title: Re: jQuery: .on() instead of .live()
Post by: live627 on February 3rd, 2013, 03:53 PM
I got rid of the second event and now the first one works.

:edit: Beaten to the punch :P
Title: Re: jQuery: .on() instead of .live()
Post by: MultiformeIngegno on February 3rd, 2013, 04:03 PM
Quote from Dragooon on February 3rd, 2013, 03:49 PM
Two things

1) You're using the function wrong, it should be (similarly for the mouseleave function)
Code: [Select]
jQuery(document.body).on("mouseenter", "#ultimecomunicazioni", function() {
        jQuery('<span id="ultimecomunicazioni_appear" style="font-weight:normal;margin-left:5px">(<a style="color:grey" href="//google.it">tutte</a>)</span>').appendTo(jQuery(this));
 });
Yup, this works now ;)
http://jsfiddle.net/5xS6W/1/
Quote
2) You're delegating events to an ID, that's pointless since you're only supposed to have one element in the DOM with the same ID. You might as well use bind after document.load
Uhm, anyway the documentation(http://api.jquery.com/bind/) says:
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.
Title: Re: jQuery: .on() instead of .live()
Post by: MultiformeIngegno on February 3rd, 2013, 04:10 PM
What about this?
Code: [Select]
$(document).on("mouseenter mouseleave", "#ultimecomunicazioni" , function(e) {
    if(e.type === 'mouseenter'){
        $(this).append('<span id="ultimecomunicazioni_appear" style="font-weight:normal;margin-left:5px">(<a style="color:grey" href="blahblah/">tutte</a>)</span>');
    } else {
        $('#ultimecomunicazioni_appear').remove();
    }
});
Title: Re: jQuery: .on() instead of .live()
Post by: Nao on February 7th, 2013, 07:32 PM
This one shouldn't be a problem... Should it?