I have a problem with element which is both draggable and also has a click event.
$(\'.drag\').mousedown(function() {
//...
});
$(\'.class\').click(function
In my case selected answer didn't worked. So here is my solution which worked properly(may be useful for someone):
var dragging = 0;
$(document).mousedown(function() {
dragging = 0;
$(document).mousemove(function(){
dragging = 1;
});
});
$('.class').click(function(e) {
e.preventDefault();
if (dragging == 0){
alert('it was click');
}
else{
alert('it was a drag');
}
});
Also you could probably do something with the mousemove and mousedown events together to disable the click event:
var dragging = 0;
$('.drag').mousedown(function() {
$(document).mousemove(function(){
dragging = 1;
});
});
$(document).mouseup(function(){
dragging = 0;
$(document).unbind('mousemove');
});
$('.class').click(function() {
if (dragging == 0){
// default behaviour goes here
}
else return false;
)};
I noticed that if the drag event is registered prior to click event then the problem described will not happen. Here is an example code:
This code create the mentioned problem:
var that = this;
var btnId = "button_" + this.getId();
var minView = $("<div>", {"id":btnId, style:"position:absolute; top:"
+ this.options.style.top + ";left:" + this.options.style.left + ";border:1px solid gray;padding:2px"});
minView.html(this.getMinimizedTitle());
minView.click(function expendWidget(event) {
$("#" + btnId).remove();
that.element.css({"left":that.options.style.left, "right":that.options.style.right});
that.element.show();
});
minView.draggable();
minView.on("drag", this.handleDrag.bind(this));
this.element.parent().append(minView);
this code does not create the problem:
var that = this;
var btnId = "button_" + this.getId();
var minView = $("<div>", {"id":btnId, style:"position:absolute; top:"
+ this.options.style.top + ";left:" + this.options.style.left + ";border:1px solid gray;padding:2px"});
minView.html(this.getMinimizedTitle());
minView.draggable();
minView.on("drag", this.handleDrag.bind(this));
minView.click(function expendWidget(event) {
$("#" + btnId).remove();
that.element.css({"left":that.options.style.left, "right":that.options.style.right});
that.element.show();
});
this.element.parent().append(minView);
It's ok, but you should alway remember, that user can move mouse slightly during the click and don't notice that. So he'd think hi clicked and you – that he dragged
You should be able to do that by stopping the propagation on the mousedown event.
$('.drag').mousedown(function(event){
event.stopPropagation();
});
You may have to make sure that this event is attached before the click event though.