Reputation: 4491
I have a contenteditable div for use as a rich text editor. Usually, the div should be draggable. But when the div is focused, I need to turn off the draggable function so I can select text by clicking and dragging.
So, I'm trying to use an if statement like so
if (!$('.elemText').is(':focus')) {
$('.elemContainer').draggable();
};
This is not taking effect though, when I focus the contenteditable div.
Similarly, if I reverse it so the div is only draggable when focused. This doesn't take effect either.
if ($('.elemText').is(':focus')) {
$('.elemContainer').draggable();
};
I'm also using some other javascript for handling focus and blur events.
$('.elemText').on({
focus: function() {
if (!$(this).data('disabled')) this.blur()
},
dblclick: function() {
$(this).data('disabled', true);
this.focus()
},
blur: function() {
$(this).data('disabled', false);
}
});
Upvotes: 1
Views: 843
Reputation: 18392
DONT use destroy! Get on with event.Propagation due to draggable or other events. If you guy enable event propgation on draggable for the given "editable"-div this solution will work fine. without destroying anything! The Problem is about draggable... draggable will prevent your click focus event in your editable div ... thats why its not working. Btw... you just need that smart code:
$('.elemContainer').draggable();
$('.elemText').on({
click: function() {
$(this).focus();
},
focus: function() {
$('.elemContainer').draggable({ disabled: true });
},
blur: function() {
$('.elemContainer').draggable({ disabled: false });
}
});
Upvotes: 1
Reputation: 5136
Use destroy
method.
This method removes the draggable functionality completely. This will return the element back to its pre-init state.
So you can do it like this : jsFiddle LIVE DEMO
$('.elemContainer').draggable();
$('.elemText').on({
focus: function() {
if (!$(this).data('disabled')) this.blur();
},
dblclick: function() {
$('.elemContainer').draggable('destroy');
$(this).data('disabled', true);
this.focus();
},
blur: function() {
$('.elemContainer').draggable();
$(this).data('disabled', false);
}
});
For more info read the API Documentation
Upvotes: 1
Reputation: 2163
You have to assign the Draggable function every time you're focusing or blurring on the element. I have updated your JSFiddle as can be seen here:
$(document).ready(function() { $('.elemContainer').draggable(); });
$(".elemText").on({
focus: function() {
$('.elemContainer').draggable("destroy");
if (!$(this).data('disabled'))
this.blur();
}, dblclick: function() {
$(this).data('disabled', true);
this.focus()
}, blur: function() {
$('.elemContainer').draggable();
$(this).data('disabled', false);
}
});
Every time you take focus out of the textbox, the item is being made draggable
, and when you focus on it, the .draggable("destroy");
removes the dragging feature.
Upvotes: 1