tuyenle tuyenle - 1 month ago 15
jQuery Question

mouseup is not fired after mousedown

the mouseup is not activated after mousedown. I'm not sure why. But if I uncomment the line

$(this).replaceWith("<div class=" + "'" + $canvas.replace(".", " ") + "'" + "></div>");


then the mouseup works normally. Here is the piece of code

var onmousemove = function ($canvas) {
// Painting the map with canvas
$map_canvas.mousedown(function () {
var ignoreMouseMove = false;
mouseDownFired = true;



$(".map .row div").mousemove(function (e) {

if (ignoreMouseMove) return;
//$(this).replaceWith("<div class=" + "'" + $canvas.replace(".", " ") + "'" + "></div>");

moveCanvas($canvas, e)
}).mouseup(function () {
ignoreMouseMove = true;
});


});

var paletteClone = $(document).clone(true); // bound handler for .palette div

};



var moveCanvas = function ($canvas, e) {
$(".map ul li." + $canvas).offset({
left: e.pageX - 30,
top: e.pageY - 30
});
};

Answer

You are binding the mouseup event to a DOM element which you then replace in the mousemove event - the mouseup event cannot run because the element is no longer on the page.

An alternative is to bind the mouseup event using the on function using the parent of .map .row - this binds the event to the parent instead so elements which are added still get behaviours as you expect.

var onmousemove = function ($canvas) {
   // Painting the map with canvas
    $map_canvas.mousedown(function () {
        var ignoreMouseMove = false;
        mouseDownFired = true;

        $(".map .row").on("mousemove", "div", (function (e) {

            if (ignoreMouseMove) return;

            // this is now OK - event bound to parent 
            $(this).replaceWith("<div class=" + "'" + $canvas.replace(".", " ") + "'" + "></div>");

            moveCanvas($canvas, e)
        }).on("mouseup", "div", function () {
            ignoreMouseMove = true;
        });


    });

    var paletteClone = $(document).clone(true);     // bound handler for .palette div

};



var moveCanvas = function ($canvas, e) {
    $(".map ul li." + $canvas).offset({
        left: e.pageX - 30,
        top: e.pageY - 30
    });
};
Comments