Samsquanch Samsquanch - 3 months ago 29
Javascript Question

mouseup() in a mousedown() called multiple times

$("#canvas").mousedown(function(e){
   var X1 = (e.pageX - this.offsetLeft) - 8;
   var Y1 = (e.pageY - this.offsetTop) - 8;
       
   $("#canvas").mouseup(function(e){
      var X2 = (e.pageX - this.offsetLeft) - 8;
      var Y2 = (e.pageY - this.offsetTop) - 8;
alert(X1 + " " + X2 + " " Y1 + " " + Y2);
});
});


The problem I'm having with this is that after the first time the function is called (the first time works fine, and as expected) the mouseup function seems to be called multiple time (i.e. multiple alerts will display instead of just the first). Is there a way to prevent this from happening, or a better way to code this?

Thanks

Answer

that's because the mouseup event is bound every time mousedown event fires.
you can simply add $("#canvas").unbind('mouseup'); at the end of mouseup function.

$("#canvas").mousedown(function(e){
        var X1 = (e.pageX - this.offsetLeft) - 8;
        var Y1 = (e.pageY - this.offsetTop) - 8;

        $("#canvas").mouseup(function(e){
            var X2 = (e.pageX - this.offsetLeft) - 8;
            var Y2 = (e.pageY - this.offsetTop) - 8;
            alert(X1 + " " + X2 + " " Y1 + " " + Y2);
            $("#canvas").unbind('mouseup');
        });
});
Comments