Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jquery ui droppable insert text in textarea at mouse pointer

I am trying to drag and drop into a textarea using jquery ui draggable/droppable. I set the textarea as droppable. I am able to fire off events when the drop happens but I can't figure out how to determine exactly in which position in the textarea the 'drop' took place.

Basically I would like to insert text at the precise position in the textarea where the drop took place.

Google isn't helping me right now and it makes me sad.

Example:

<html><head><title>Drag Drop Test</title>
<link rel="stylesheet" href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.6/themes/base/jquery-ui.css" type="text/css" media="all" />
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.3/jquery.min.js" type="text/javascript"></script>
<script src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.6/jquery-ui.min.js" type="text/javascript"></script>

<script>
  $(document).ready(function(){

    $( "#catalog li" ).draggable({
      appendTo: "body",
      helper: "clone"
    });

    $( "#mytext" ).droppable({
      accept: ":not(.ui-sortable-helper)",
      drop: function( event, ui ) {
        console.log(ui.position);
        // figure out where in the textarea this is
        // drop in some string
      }
    });
  });
  </script>
</head>
</body>

<div id="products">
  <div id="catalog">
    <h3><a href="#">T-Shirts</a></h3>
    <div>
      <ul>
        <li>Lolcat Shirt</li>
        <li>Cheezeburger Shirt</li>
        <li>Buckit Shirt</li>
      </ul>
    </div>
  </div>
</div>

<textarea id="mytext" cols="60" rows="20">Just some random text.</textarea>

</body></html>

So, in the above example, how do I find out which position in the textarea a 'drop' happened of one of the catalog li elements and then how do I put in a string into the textarea at that exact position?

Meaning, if I drag 'Lolcat Shirt' into the #mytext textarea and drop it between 'random' and 'text' I would like the #mytext textarea value to change to 'Just some random Lolcat Shirt text.'

Is this possible? Your help would be greatly appreciated. Thanks in advance!

like image 845
Bubba Raskin Avatar asked Nov 09 '10 08:11

Bubba Raskin


1 Answers

This is not really easy in browsers except IE, because you have to work with ranges, and other browsers does'nt have any methods that work with coordinates inside a range(what you need, to place the text there).

But somehow you try to reinvent the wheel. Most browsers(maybe all) allow to move selected text into a textarea, so what you have to do is: onmousedown select the text of the <li> (instead of making it draggable)

like image 95
Dr.Molle Avatar answered Oct 11 '22 20:10

Dr.Molle