Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I make an element draggable, but not its child elements, using jQuery UI?

Tags:

For example, I want to have this:

<div class="draggable"> <p>Text that can be selected</p> </div> 
like image 307
Leo Jiang Avatar asked Dec 30 '11 16:12

Leo Jiang


People also ask

How do you make a draggable object?

To make an object draggable set draggable=true on that element. Just about anything can be drag-enabled: images, files, links, files, or any markup on your page. Our example creates an interface to rearrange columns that have been laid out with CSS Grid.

What is jQuery draggable?

Draggable() Method This method allows the elements to be dragged with the help of mouse. Using jQuery UI, we can make the DOM(Document Object Model) elements to drag anywhere within the view port. This can be done by clicking on the draggable object by mouse and dragging it anywhere within the view port.


2 Answers

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.

like image 106
David Thomas Avatar answered Sep 17 '22 15:09

David Thomas


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.

like image 30
Timo Kähkönen Avatar answered Sep 17 '22 15:09

Timo Kähkönen