javascript - Cancel incoming jQuery click event if mouse is moved after mousedown -


i'm trying prevent click event firing if mouse moved after 'mousedown' event. i'm doing manually via conditionals , booleans. still don't have working how want, , feel it's poor approach accomplishing this.

var mousemove = false; var mousedown = false; var cancelclick = false;  $('.example').click( function() {     if (!cancelclick) {         if ( $(this).attr('id') === 'example-green') {             $(this).attr('id', 'example-blue');         } else {             $(this).attr('id', 'example-green');         }       }     cancelclick = false; });  $('.example').mousedown( function() {     mousedown = true; });  $('.example').mouseup( function() {     if (mousemove) {         cancelclick = true;     }     mousedown = false;     mousemove = false; });  $('.example').mousemove( function() {     if (mousedown) {         mousemove = true;     } }); 

http://jsfiddle.net/agf6g/4/

is there simpler way achieve this? preferably 1 prevents click events being processed, or removes them pending event queue (i'm not sure if queued until after release mouse). way callbacks aren't coupled implementation of this.

i store x/y coordinates of mouse on mousedown , compare current coordinates in click.

$('.example')    .on('mousedown', function() {         $(this).data("initcoords", { x: event.clientx, y: event.clienty });     })    .on('click', function() {         var initcoords = $(this).data("initcoords") || { x: 0, y: 0 };          if (event.clientx === initcoords.x && event.clienty === initcoords.y) {             if ( $(this).attr('id') === 'example-green') {                 $(this).attr('id', 'example-blue');             } else {                 $(this).attr('id', 'example-green');             }               $(this).data('initcoords', {x:-1, y:-1});         }     }); 

http://jsfiddle.net/zp2y2/8/


you toggle click event on , off. little more concise wonder overhead of setting event handlers compared method above.

$('.example')     .on('mousedown', function() { $(this).one("click", handleclick); })     .on('mousemove mouseout', function() { $(this).off('click'); });  function handleclick(){     var $el = $('.example');     if ( $el.attr('id') === 'example-green') {         $el.attr('id', 'example-blue');     } else {         $el.attr('id', 'example-green');     }   } 

http://jsfiddle.net/du7zx/


Comments

Popular posts from this blog

php - render data via PDO::FETCH_FUNC vs loop -

c++ - OpenCV Error: Assertion failed <scn == 3 ::scn == 4> in unknown function, -

The canvas has been tainted by cross-origin data in chrome only -