Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you make text selectable on a jQuery draggable div?

I made a div draggable using jQuery. However, there is some text in that box, and I would still like to be able to copy and paste the text, but when I make an item draggable well when I click on the box it starts to move the box?

like image 740
SamFisher83 Avatar asked Jun 17 '12 21:06

SamFisher83


People also ask

How do I make text draggable?

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.

Can a div be draggable?

Btw, you can make a div "draggable" without JS, but you cannot "drag" it.


2 Answers

Use the cancel option when making the element draggable.

Prevents dragging from starting on specified elements.

$('.selector').draggable({ cancel: '.text' }); 
like image 121
Nikolay Lapitskiy Avatar answered Oct 22 '22 09:10

Nikolay Lapitskiy


It doesn't make sense to allow dragging AND selecting text on the same element. However, if you keep thinking it's necessary, two things come to my mind:

Solution 1:

You can add a "handler" that will be the only child receiving the mouse down/up events to drag the div. For instance:

<div id="draggable">
  <div class="handler"></div>
  <div class="text">This is a selectable text</div>
</div>

And in your JavaScript code:

var draggableDiv = $('#draggable');
draggableDiv.draggable({
  handle: $('.text', draggableDiv)
});

Solution 2:

You can disable the draggable thing when a user try to select text:

<div id="draggable">
  <div class="text">This is a text</div>
</div>

And in your JavaScript code:

var draggableDiv = $('#draggable').draggable();
$('.text', draggableDiv).mousedown(function(ev) {
  draggableDiv.draggable('disable');
}).mouseup(function(ev) {
  draggableDiv.draggable('enable');
});

When someone tries to select something in .text, the draggable process is disabled.

The first solution is the proper one.

like image 40
ldiqual Avatar answered Oct 22 '22 10:10

ldiqual