2

I wonder how I can rewrite the following listener with jQuery on()

$('.box').live({
        mouseenter:
        function() {
            $(this).children('.menu').stop(true, true).fadeIn(fadeIn);
        },
        mouseleave:
        function() {
            $(this).children('.menu').stop(true, true).fadeOut(fadeOut);
        }
    });

Any ideas?

ajacian81
  • 7,419
  • 9
  • 51
  • 64
matt
  • 42,713
  • 103
  • 264
  • 397
  • 1
    See http://stackoverflow.com/questions/8021436/jquery-1-7-turning-live-into-on and the documentation http://api.jquery.com/live/, http://api.jquery.com/on/. You will find the information about how to convert `.live` to `.on` there. – Felix Kling Jul 19 '12 at 11:11

2 Answers2

4
$(document).on('hover', '.box', function(e) {
  if( e.type == 'mouseenter') {
    $(this).children('.menu').stop(true, true).fadeIn(fadeIn);
  } else {
    $(this).children('.menu').stop(true, true).fadeOut(fadeOut);
  }
});

Instead of document it would be better to use any parent element of .box which is not dynamic.

Read about .on().

Syntax of .on() for delegate event (aka live event) is:

$( StaticParent ).on( eventName, target, handlerFunction );
thecodeparadox
  • 86,271
  • 21
  • 138
  • 164
2

For exact .on equivalent:

$(document).on({
    mouseenter: function() {
        $(this).children('.menu').stop(true, true).fadeIn(fadeIn);
    },
    mouseleave: function() {
        $(this).children('.menu').stop(true, true).fadeOut(fadeOut);
    }
}, '.box');

Though the main benefit here is that you don't need to use document, you can just use the closest parent that is guaranteed to exist for the lifetime of the page.

Esailija
  • 138,174
  • 23
  • 272
  • 326