0

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)

1 Answer 1

2

I strongly recommend using a JavaScript library which smooths out the cross-browser differences when working with ranges and selections: Rangy.

A cross-browser JavaScript range and selection library. It provides a simple standards-based API for performing common DOM Range and Selection tasks in all major browsers, abstracting away the wildly different implementations of this functionality between Internet Explorer and DOM-compliant browsers.

For manipulating selections in <textarea> and <input type="text"> elements, see see Rangy's poorly-named and svelter twin project, Rangyinputs.


How to get the selected text from TEXTAREA and how to replace it with the tags?

Check out the Rangy CSS Class Applier Module (and associated demo page).

Sign up to request clarification or add additional context in comments.

1 Comment

i have a question related to this: what is the proper way(cross-browser compatible) to call a javascript function inside onMouseDown event ? Is this onMouseDown = "myFunction();" correct way ? It does works though, I want to know the correct way because I am trying to learn now.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.