jQuery: .on() instead of .live()

MultiformeIngegno

  • Posts: 1,337

Dragooon

  • I can code! Really!
  • polygon.com has to be one of the best sites I've seen recently.
  • Posts: 1,841
Re: jQuery: .on() instead of .live()
« Reply #1, 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
The way it's meant to be

live627

  • Should five per cent appear too small / Be thankful I don't take it all / 'Cause I'm the taxman, yeah I'm the taxman
  • Posts: 1,670
A confident man keeps quiet.whereas a frightened man keeps talking, hiding his fear.

MultiformeIngegno

  • Posts: 1,337
Re: jQuery: .on() instead of .live()
« Reply #3, 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 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.
Re: jQuery: .on() instead of .live()
« Reply #4, on February 3rd, 2013, 04:10 PM »Last edited on February 3rd, 2013, 04:18 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();
    }
});

Nao

  • Dadman with a boy
  • Posts: 16,082