Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

smilies to textarea on click

I have a little question

I want to click on my smileys and insert the text to the textarea. and when I want to add a smiley later, the smiley should be added to the cursor position and not at the end in the textarea.

This is my html code:

<textarea id="description" name="description"></textarea>

<div id="emoticons">
    <a href="#" title=":)"><img alt=":)" border="0" src="/images/emoticon-happy.png" /></a>
    <a href="#" title=":("><img alt=":(" border="0" src="/images/emoticon-unhappy.png" /></a>
    <a href="#" title=":o"><img alt=":o" border="0" src="/images/emoticon-surprised.png" /></a>
</div>

This is my JS code:

$('#emoticons a').click(function(){

    var smiley = $(this).attr('title');
    $('#description').val($('#description').val()+" "+smiley+" ");

});

Here you can see the result (NO WRAP - BODY) http://jsfiddle.net/JVDES/8/

I use an extern JS file for my javascript-code...
Do you know why the code isn't running in NO WRAP - HEAD mode? http://jsfiddle.net/JVDES/9/

Thanks for helping

Regards bernte

like image 654
bernte Avatar asked Dec 06 '22 13:12

bernte


2 Answers

Also, you can use something this function:

function ins2pos(str, id) {
   var TextArea = document.getElementById(id);
   var val = TextArea.value;
   var before = val.substring(0, TextArea.selectionStart);
   var after = val.substring(TextArea.selectionEnd, val.length);
   TextArea.value = before + str + after;
}

For your example, look here.


UPD 1:

To set cursor at specified position, use the next function:

function setCursor(elem, pos) {
   if (elem.setSelectionRange) {
      elem.focus();
      elem.setSelectionRange(pos, pos);
   } else if (elem.createTextRange) {
      var range = elem.createTextRange();
      range.collapse(true);
      range.moveEnd('character', pos);
      range.moveStart('character', pos);
      range.select();
   }
}

I updated code on jsFiddle, so, to view new example, look here.

like image 121
Victor Avatar answered Dec 09 '22 03:12

Victor


Try this - http://jsfiddle.net/JVDES/12/

Credit for the caret position function goes to - https://stackoverflow.com/a/1891567/981134

like image 30
Zoltan Toth Avatar answered Dec 09 '22 04:12

Zoltan Toth