Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Removing mouseenter event on dynamically created elements with jQuery

I'm having some trouble with my Javascript when using jQuery UI's sortable method on dynamically created elements. When I hover an image it displays a larger version of the image which follows the cursor within the thumbnail. Then, when I'm sorting/dragging an image it displays the larger image with it's position set to far away from the thumbnail. The larger image should be hidden when sorting :-)

I've made a screenr so it's easier for you to see what I mean: http://screenr.com/jjv8

My code for hooking up the events:

// Selected photos hover
$('ul li img').live('mouseenter', function () {
    var img = $(this);
    var imgDiv = $(this).parent().find('.hover-image');
    img.mousemove(function (e) {
        imgDiv.show();
        var x = e.pageX;
        var y = e.pageY - 50;
        imgDiv.css({ "top": y + "px", "left": x + "px" });
    });
});

$('ul li img').live('mouseleave', function () {
    $(this).parent().find('.hover-image').fadeOut('fast');
});

And my code for sorting:

selectedPhotosList.sortable({
    handle: '.selected-thumbnail-image',
    start: function (event, ui) {
        ui.item.find('.selected-thumbnail-image').die('mouseenter');
        ui.item.find('.hover-image').hide();
    }
});

Yes, I'm using .live() since this is a datatype which resides in Umbraco CMS which uses an older version of jQuery, so .on() doesn't work :-)

Anyone got a hint on how to get this to work?

EDIT

I found the bug:

In my .live('mouseenter', function()... I'm calling imgDiv.show(); every time the cursor moves.

Doing it like this works:

// Selected photos hover
$('ul li img').live('mouseenter', function () {
    var img = $(this);
    var imgDiv = $(this).parent().find('.hover-image');
    imgDiv.show();
     img.mousemove(function (e) {
         var x = e.pageX;
         var y = e.pageY - 50;
         imgDiv.css({ "top": y + "px", "left": x + "px" });
     });
});

$('ul li img').live('mouseleave', function () {
    $(this).parent().find('.hover-image').fadeOut('fast');
});

However, this creates another bug when using IE.: Screenr: http://screenr.com/1Iv8

The hover image is shown once before actually triggering the mousemove function :-/ Any way to overrule this?

like image 631
bomortensen Avatar asked Aug 30 '26 02:08

bomortensen


1 Answers

I'd suggest:

$('ul li img').off('mouseenter');

like image 138
Snake Eyes Avatar answered Sep 01 '26 18:09

Snake Eyes