1

I have created this jsfiddle for try to explain what Im trying to do

http://jsfiddle.net/nonyck/tyyCN/

$('.autoresize').bind('paste', function(e) {
    e.preventDefault();
    var data = e.originalEvent.clipboardData.getData('text');
     if(data.match("http://.*?.(jpg|png|gif)")) {
       $('.autoresize').val($('.autoresize').val() + "<image src='" + data + "' >");
     } else { 
       $('.autoresize').val( $('.autoresize').val() + data);
     }
});

What Im trying is to get the paste event, then modify it and return it back exactly where is the focus, atm this example just returns the content to the end.

So if the user is in the line 2, and pastes some content there, put the modified content there, and not at the end of the document.

Is there a way to return the value at the right place ??

Nonyck
  • 652
  • 1
  • 12
  • 28

1 Answers1

2

You can get the caret position within the textarea using jQuery to determine where the user wants to paste the text: Cursor position in a textarea (character index, not x/y coordinates)

Then insert your data into that position. See updated fiddle: http://jsfiddle.net/tyyCN/1/

if(data.match("http://.*?.(jpg|png|gif)")) {
         var caret = $(this).getCursorPosition();
         var insert = "<image src='" + data + "' >";
         var val = $('.autoresize').val();
       $('.autoresize').val(val.substring(0, caret) + insert + val.substring(caret, (val.length)));
     }
Community
  • 1
  • 1
CodingIntrigue
  • 75,930
  • 30
  • 170
  • 176
  • Works great! Can the cursor position be fixed when you do a paste ? atm paste an item places the cursor at the end of the textarea – Nonyck May 29 '13 at 12:51
  • Sure, there are a few tricks used in this post: http://stackoverflow.com/questions/499126/jquery-set-cursor-position-in-text-area – CodingIntrigue May 29 '13 at 12:52