Saturday, 16 November 2013

Online Text Editor in Javascript

here I have pic of my simply created online text editor, actually I was working on a project and it needs a form that also can edit text like making it Bold, Italic, underline and many things.
So, In this smallest project I took Text area HTML DOM and few buttons as it is obvious in the above pic.
When person on client side starts writing then simply he or she may need to decorate his or her writing since in database as we know that it will simply store like ordinary data and when we retrieve it it simply display it in string format. To make it decor able after saving we will have to add html tags like </br> to break line and <b></b> to make text bold.

java script function code 

function editor(domofhtml) {


            var Field = document.getElementById('TextArea1');
            var val = Field.value;
            var selected_txt = val.substring(Field.selectionStart, Field.selectionEnd);
            var before_txt = val.substring(0, Field.selectionStart);
            var after_txt = val.substring(Field.selectionEnd, val.length);
            Field.value = before_txt + '<'+ domofhtml +'>' + selected_txt + '</'+ domofhtml +'>' + after_txt;
       
        }
to know about list of in build function and object of java script click on this link and you would be better able to know how they are working in the above function.

here 'TextArea1' is ID of text area box in the above pic. Field store the reference of this and Val it's value and we will have to find start index of selected text and end index of this text so that we can apply our HTML tags 'domofhtml ' is parameter so that we can pass different HTML DOM through same function of click of various type buttons to edit text in TextArea.

Now on the Bold button at onclick event add this function like this

<input id="Button1" type="button" value="Bold" onclick="editor('b');" />

To make Italic text do this on italic button 

<input id="Button2" type="button"  value="Italic" onclick="editor('i');" />
 
and similarly you can add many Tags.

Thank you for giving time, Have a nice day..