3

I want to implement the make bold and put underline functions on my own. For this, I need to get the text which is marked like this:

enter image description here

How can I do this with JavaScript?

Simon Adcock
  • 3,554
  • 3
  • 25
  • 41
doniyor
  • 36,596
  • 57
  • 175
  • 260
  • You mean that you want to find all texts containing 'text which is marked' and make them bold and underlned? – Maria Ioannidou Apr 14 '13 at 09:49
  • @MariaIoannidou, i have a button called ``BOLD``, i want that if user selects a word or sentence and hits ``BOLD``, the selected text should get bold or should be set in between some signs like ```` – doniyor Apr 14 '13 at 09:51
  • 1
    See [this](http://stackoverflow.com/questions/6251937/how-to-get-selecteduser-highlighted-text-in-contenteditable-element-and-replac) and http://jsfiddle.net/dKaJ3/2/ – palaѕн Apr 14 '13 at 09:52
  • @PalashMondal, i cannot attach click event, http://jsfiddle.net/NjW5a/36/ can you pls take a look – doniyor Apr 14 '13 at 10:35

2 Answers2

4
var start = element.selectionStart;
var end = element.selectionEnd;
var sel = element.value.substring(start, end);
DarkBee
  • 16,592
  • 6
  • 46
  • 58
1

Based on this and this questions, this fiddle demo shows how you can implement make bold and toggle bold functionality on selected text.

The js function to make selected text bold is:

function makeBold() {
    var selection = window.getSelection();
    if (selection.rangeCount) {
        var range = selection.getRangeAt(0).cloneRange();
        var newNode = document.createElement("b");
        range.surroundContents(newNode);
        selection.removeAllRanges();
        selection.addRange(range);
    }
}
Community
  • 1
  • 1
Maria Ioannidou
  • 1,544
  • 1
  • 15
  • 36