Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery Drag & Drop into a Text Area

Using jQuery, and looking to let user drag a placeholder into a text area.

Each placeholder is a <span> which has a class='placeholder'. The text area id is simply 'main_text'.

So, user should be able to drag each placeholder span on top of text area, drop it, and then text gets inserted.

Most desirable effect would be to insert text where they drop the placeholder, but I have pretty much given up on that one. At this point, just to get it working so it inserts the text anywhere at all would be a good start.

Has anyone successfully done this? Thanks -

like image 209
OneNerd Avatar asked Dec 17 '09 15:12

OneNerd


People also ask

How do you drag in JavaScript?

Introduction to JavaScript Drag and Drop API To drag an image, you simply hold the mouse button down and then move it. To drag the text, you need to highlight some text and drag it in the same way as you would drag an image.

Why is jQuery draggable not working?

You have one of these problems: Your jQuery or jQuery UI Javascript path files are wrong. Your jQuery UI does not include draggable. Your jQuery or jQuery UI Javascript files are corrupted.

What does draggable mean in HTML?

The draggable global attribute is an enumerated attribute that indicates whether the element can be dragged, either with native browser behavior or the HTML Drag and Drop API. draggable can have the following values: true : the element can be dragged.


1 Answers

I don't think you can use the textarea directly as droppable thus I made a little hack which on drag-start positions a div directly over the textarea. The div is the actual droppable which then inserts the text of the draggable into the textarea

Check here for a demo

http://jsbin.com/egefi (http://jsbin.com/egefi/edit for the code)

It inserts at current textcaret position I don't think inserting at current mouse cursor position is even possible.

function insertAtCaret(area, text) {
    //... adapted from http://www.scottklarr.com/topic/425/how-to-insert-text-into-a-textarea-where-the-cursor-is/
}

$(document).ready(function() {
    var options = {
        accept: "span.placeholder",       
        drop: function(ev, ui) {
            insertAtCaret($("textarea#main_text").get(0), ui.draggable.eq(0).text());
        }
    };

    $("span.placeholder").draggable({
        helper:'clone',
        start: function(event, ui) {
            var txta = $("textarea#main_text");
            $("div#pseudodroppable").css({
                position:"absolute",
                top:txta.position().top,
                left:txta.position().left,
                width:txta.width(),
                height:txta.height()
            }).droppable(options).show();
        },
        stop: function(event, ui) {
            $("div#pseudodroppable").droppable('destroy').hide();
        }
    });
});
like image 61
jitter Avatar answered Nov 20 '22 11:11

jitter