8

I'd like to have a div that is at the same time editable and draggable, using jQuery UI. Content editability seems to work only if draggable is not enabled. Am I missing something? I'm using jQuery 1.4.4 and jQuery UI 1.8.9

JavaScript:

$(function(){
    $('#draggable').draggable();
});  

HTML:

<div contenteditable="true" id="draggable">TEXT</div>
Yi Jiang
  • 49,435
  • 16
  • 136
  • 136
Tommy
  • 1,219
  • 11
  • 18

4 Answers4

16

While the answer provided by Krule will work, there is a usability problem. The cursor will always appear at the beginning of the editable area when clicked. This makes it impossible to select text with the mouse. The only way to jump to an area of text is to use arrow keys. I don't believe this is acceptable.

The only solution I have been able to come up with is to use a "handle" for dragging:

<style>
.positionable {
    position:absolute;
    width:400px; height:200px;
}
.drag_handle {
    position:absolute;
    top:-8px; left:-8px;
    background-color:#FFF; color:#000;
    width:14px; height:14px;
    cursor:move;
    font-size:14px; line-height:14px;
    font-weight:bold;
    text-align:center;
    border:1px solid #000;
}
.editable {
    outline:none;
    width:100%; height:100%;
}
</style>

<div class="positionable">
    <div class="drag_handle">+</div>
    <div class="editable" contentEditable="TRUE">type here...</div>
</div>

<script>
    $('.positionable').draggable({handle: '.drag_handle'});
</script>
tybro0103
  • 48,327
  • 33
  • 144
  • 170
  • 3
    Useful snippet. I was worried that I'm the only one with problem, apparently all questions have been already asked/answered. – Mars Robertson Nov 14 '12 at 22:08
13

It is working but the jQuery draggable is hijacking click event. You can still tab to it. This is a quick fix.

$('#draggable').draggable().bind('click', function(){
  $(this).focus();
})
Krule
  • 6,468
  • 3
  • 34
  • 56
  • The problem with this is that focus() sets the cursor at the beginning, rather than where it was clicked. – tybro0103 Jun 30 '11 at 18:01
3

you can give this div a 'parent div' and add draggable event to it parent. then use offical API 'cancel'

HTML:

<div id="draggable">
    <div contenteditable="true" class="editable">TEXT</div>
</div>

JS:

 $('#draggable').draggable({cancel: '.editable'});
oliver34
  • 330
  • 2
  • 7
1

This has driven me nuts - but there's a way to do it without a drag handle. Use a different tag for your editable element, and prevent that element from being dragged http://api.jqueryui.com/draggable/#option-cancel

user3046913
  • 83
  • 1
  • 1
  • 8