Encase Selected Text With Tags In A TextArea

Something that I have tried to figure out for ages when designing the comment system for my Blog is, how are people going to know to put tags around text they want to change?

The answer to this was simple, I needed to find or create a function that recognised what piece of text the user has highlighted and to encase the tags around them myself.

For example:

If a user wanted something bold, all they would need to do is highlight the piece or area of text they wish to be bold and then press the 'B' button on the form. The relevant BOLD tags would then be encased around the word the user highlighted and all they would need to do is submit the comment..




Hey Presto!!! They are left with something BOLD!!!




The code that I used, is a JavaScript function that I found after a single search in Google. It is a basic function that can be added to any event of a form that you want, such as a button or an image or a text input.


function addTags(Tag,fTag,Message) {
var obj = document.getElementById('comments');
obj.focus();
if (document.selection && document.selection.createRange) // Internet Explorer
{
sel = document.selection.createRange();
if (sel.parentElement() == obj) sel.text = Tag + sel.text + fTag;
}
else if (typeof(obj) != "undefined") // Firefox
{
var longueur = parseInt(obj.value.length);
var selStart = obj.selectionStart;
var selEnd = obj.selectionEnd;
obj.value = obj.value.substring(0,selStart) + Tag +
obj.value.substring(selStart,selEnd) + fTag + obj.value.substring(selEnd,longueur);
}
else obj.value += Tag + fTag;
obj.focus();
}

To call this function you can use it on any element you like to trigger the function.

<img src="img/buttons/bold.png" onClick="addTags('','')" title="bold">

Good luck with the code.

    Recent Posts

    Blog By Month

    Blog By Topic

    Follow Me

    Twitter Updates