For example, I want to have this:
Text that can be selected
You can override the start
function as part of the options to initialization. Returning false here will break out of it prematurely. To access the mouse event created when clicking, you can access the originalEvent
property on the jQuery event.
$(".draggable").draggable({
start: function(event, ui) {
return event.originalEvent.target === this;
}
});
This allows for only the parent to be draggable. You can replace this
with whatever element you want to be the only draggable item, just make sure it is the dom node getting compared.
Plunkr example
There can be other elements as children than p. In this case you have to use space selector:
$(".draggable").draggable({cancel: ".draggable *"});
The working example is at JSFIDDLE.
It uses space selector, which selects all children of element whether they are children or grand children. Space selector example at w3schools.
The downside of this is that all the textnodes have to be wrapped inside tag, eg. span, div, p. If they are not inside tag, the * selector cannot match them. To remain plain textnodes selectable, you have to use more complex code, because CSS and jQuery doesn't contain selector for plain textnodes. You can eg. use your own tag for wrapping textnodes. The reason for custom node is that it decreases the possibility for this custom element to be styled accidentally (like when using span etc.), in this case we name it 'custom':
$(".draggable").draggable({cancel:'.draggable *'})
.contents().filter(function() {return this.nodeType == Node.TEXT_NODE;})
.wrap('<custom></custom>');
The above at JSFIDDLE. Now also plain textnodes are selectable. Things changes if you add dynamically afterwards more textnodes into the draggable element. Then you have to wrap them again.
You can use the cancel
option, which accepts a selector for child elements of the draggable object that should not allow dragging:
$('.draggable').draggable({cancel : 'p'});
JS Fiddle demo.