I am creating a small HTML editor using jQuery. I have created my own button-icons for:
- bold
- italics
- underline
- insert hyperlink
- insert image
- unordered list
- ordered list
But I donot know how to get it working. My idea:
-
bold: when user clicks on this button, selected text in the editor box() should be replaced with
<b> ..selected_text.. </b>. Otherwise, insert<b></b>at cursor position. -
italic: when user clicks on this button, selected text in the editor box() should be replaced with
<i> ..selected_text.. </i>. Otherwise, insert<i></i>at cursor position. -
same as above for Underline
-
etc….
So my question is, how to get the selected text from TEXTAREA and how to replace it with the tags? And also, how to insert a text at cursor position (ie. at that blinking line) ?
This is same as the buttons present in Stackoverflow’s editor, when you post some questions. (for example, try clicking on the BOLD button in Stackoverflow’s editor, when you have selected a text and when not selected)
I strongly recommend using a JavaScript library which smooths out the cross-browser differences when working with ranges and selections: Rangy.
Check out the Rangy CSS Class Applier Module (and associated demo page).