dee cheok dee cheok - 26 days ago 6
jQuery Question

hover change to on mousenter breaks logic

$('.masterTooltip').hover(function() {
// hover over code.
var title = $(this).attr('data-submenu');

$(this).data('tipText', title).removeAttr('title');
$('<p class="tooltip"></p>').text(title).appendTo('body');

var x = $(this).offset();
var w = $('#collapsed-menu').width();
$('.tooltip').css({ top: x.top + 'px', left: w + 'px' }).show();
}, function() {
// Hover out code
$(this).attr('title', $(this).data('tipText'));
$('.tooltip').remove();
});


My intention is to make a tooltip which shows a popup box when you hover over the
<a>
. This code works just fine, but because my HTML for this is dynamically loaded it wont work using hover.

$('#menuMain-ul').on('mouseenter', '.masterTooltip', function() {

});


This was the code only work on my dynamic HTML, but when I combine the two codes together it doesn't work. Can anyone help me use
mouseenter
to make it work?

Normal Demo try hover over the text

COMBINE DEMO noting show.

Answer

Your code is close. The issue is that when using a delegated event handler you can only assign one event handler at a time, so you need to call on() again for the mouseleave event. Try this:

$('#menuMain-ul').on('mouseenter', '.masterTooltip', function() {
    var $el = $(this);
    var title = $el.data('submenu');
    $el.data('tipText', title).removeAttr('title');
    $('<p class="tooltip"></p>').text(title).appendTo('body').css({
        top: $el.offset().top,
        left: $('#collapsed-menu').width()
    }).show();
}).on('mouseleave', '.masterTooltip', function() {
    $(this).attr('title', $(this).data('tipText'));
    $('.tooltip').remove();
});

Updated fiddle

Also note that I amended the logic slightly to follow best practices.