biera
biera

Reputation: 2699

jQuery clickable element nested in draggable one

Let's say I have got HTML code that looks as follows:

<script>
  $("#draggable").draggable();

  $("#clickable").click(function() {
    alert('CLICK!');
  });
</script>

<div id="draggable">
    <div id="clickable">        
    </div>
</div>

As you can see: clickable div is nested in draggable div. When I drag & drop draggable div using clickable div as handle click event bound to it is fired. That is not desired behaviour. I want the click event to be fired only when you click on clickable but without dragging it anywhere. Is it even possible? I want to add I'm not interested in solutions where setTimeout (or similar) is used. Here you have got jsfiddle link (note: css is added for better visibility).

Thanks for any clues!

Upvotes: 2

Views: 1240

Answers (2)

SeanCannon
SeanCannon

Reputation: 78006

Here you go:

function handleClick() {
    alert('click!');
};

$("#draggable").draggable({
    start: function () {
        $('#clickable').off('click');
    },
    stop: function () {
        setTimeout(function(){
            $('#clickable').on('click', handleClick);
        },1);
    }
});

$("#clickable").on('click', handleClick);

Demo : http://jsfiddle.net/HmK9z/

Upvotes: 3

Hanlet Esca&#241;o
Hanlet Esca&#241;o

Reputation: 17380

Use the callback of the draggable method like this:

HTML:

<div id="draggable">
    <div id="clickable">        
    </div>
</div>

JQuery:

var dragged = false;
$("#draggable").draggable({stop:function(ev,ui) { dragged = true;}});

$("#clickable").click(function() {
    if(!dragged)
        alert('CLICK!');
    dragged = false;
});

JSFiddle: http://jsfiddle.net/AJmTg/9/

Good luck!

Upvotes: 2

Related Questions