adaam
adaam

Reputation: 3706

Capturing hover end event with delegated on() event handler function in jQuery

I would like to do something similar to the mouseleave callback that the jQuery hover() function has:

Syntax:

$( selector ).mouseenter( handlerIn ).mouseleave( handlerOut );

Example hover() code:

$( "li" ).hover(
  function() {
    // handles hover event
    $( this ).append( $( "<span> ***</span>" ) );
  }, function() {
    // handles mouseout/mouseend event
    $( this ).find( "span:last" ).remove();
  }
);

I have tried attaching 2 callbacks to the on() function with no success.

Unfortunately I need to use the on() delegated event as my DOM elements I need to target have been added dynamically. Does anyone how I can achieve this?

My jQuery at the moment:

$('ul.results').on('hover', 'li', function () {
        // hover stuff here
     }, function() {
        // obviously wrong
     }
});

Upvotes: 0

Views: 294

Answers (4)

Felix
Felix

Reputation: 38102

You can chain multiple .on() like this:

$('ul.results').on('mouseenter', 'li', function( event ) {
    $( this ).append( $( "<span> ***</span>" ) );
}).on('mouseleave', 'li', function( event ) {
    $( this ).find( "span:last" ).remove();
});

Upvotes: 1

Jai
Jai

Reputation: 74738

If i have to do this then i would do it this way:

$('ul.results').on({
   mouseenter : mouseEntr
   mouseleave : mouselve
}, 'li');

function mouseEntr(){
   // mouse enter stuff here
}

function mouselve(){
   // mouse leave stuff here
}

Upvotes: 2

demonofthemist
demonofthemist

Reputation: 4199

Use this

$( "body" ).on('mouseenter', 'ul.results li', function() {
    $( this ).append( $( "<span> ***</span>" ) );
});

$( "body" ).on('mouseleave', 'ul.results li', function() {
    $( this ).find( "span:last" ).remove();
});

Upvotes: 1

Rob Schmuecker
Rob Schmuecker

Reputation: 8954

$( "someList" ).on('hover', 'li', function() {
    // handles hover event
    $( this ).append( $( "<span> ***</span>" ) );
  });
$( "someList" ).on('mouseleave', 'li', function() {
    // handles mouseout/mouseend event
    $( this ).find( "span:last" ).remove();
});

Upvotes: 1

Related Questions