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 -
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.
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.
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.
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();
}
});
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With