2

Ok, so I have these draggable elements, that also have click event handlers. The problem is that the click event is firing (and handled) when I drag the element, but what I wanted is to handle the click only when there's no dragging going on, so when the element is dragged, cancel the click event handling.

Here's a demo fiddle: http://jsfiddle.net/wsTY5/

$('div.map').draggable(options);

1 Answer 1

2

You can accomplish it with something like this:

var clicked = true;
var options = {
    containment: '.map-containment',
    cursor: 'move',
    start: function( event, ui ) {
        clicked = false;
    }
};

$('div.map').draggable(options);

var counter = 0;

var $span = $('#ClickCounter > span');
var $dummies = $('.dummy');
$dummies.click(function(){
    if(clicked){
        $span.html(++counter);
    }
    clicked = true;
});

Example:

http://jsfiddle.net/trevordowdle/wsTY5/1/

Update

Sometimes when you drag it does not register the click event depending on where you end the dragging.

var options = {
    containment: '.map-containment',
    cursor: 'move',
    start: function( event, ui ) {
        clicked = false;
    },
    stop: function( event, ui ) {
        setTimeout(function(){
            clicked = true;  
        },10);
    }
};

So I added the stop function to the options just to make sure that it would count clicks once you stop dragging.

http://jsfiddle.net/trevordowdle/wsTY5/3/

Sign up to request clarification or add additional context in comments.

3 Comments

@fduayer I'm seeing a little weird behavior where sometimes the click does not go through.. going to look into it a little more. I may have an update.
@fduayer check my update for a better solution. Thanks
@Trevor I'd recommend changing the $dummies.click listener to a $dummies.on('mouseup') listener.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.