Insert smileys into a textarea

Sometimes it’s good to have a few smiley-images beside a textarea field, and let the users insert text-smileys by clicking the correspondent image. I’m going to show how you can do this in a simple way, using Javascript.

First we have to create the Javascript function to work with.

<script type="text/javascript">
function addSmiley (txt, id) {
var div = document.getElementById(id);
div.value = '' txt ' ';
}
</script>

It’s quite simple. The function takes two parameters; the text we want to add, and the id of the textarea we want to insert the text in.

The idea is that when a user click on one of the smiley-images, the function will be called and it will insert the text. So, we have to make links out of the images.

<a href="#" onclick="addSmiley(':)', 'textarea');"><img src="smile.gif" alt="Smile" border="0"/></a>

Now when you click on smile.gif, the text “:)” will be added into the textarea.

Feel free to use these smileys:

This entry was posted in Javascript. Bookmark the permalink.

One Response to Insert smileys into a textarea

  1. Gaga says:

    hey..
    did you test the code..
    could you provide a demo..
    i modified the code

    function addSmiley (txt, ta) {
    var div = document.getElementById(ta);
    div.value = ' '+txt+' ' ;
    }



    but the problem is the smiley erases my text and gets inserted and only once.
    please check your code.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Connecting to %s