1

I want to highlight feature which will change the color of the selected text using Javascript. I am using the following method.

function android_selection_highlight(replacrmenthtml){
    try {
        if (window.getSelection) {
            sel = window.getSelection();
            var range = sel.getRangeAt(0);

            var selectionStart = $("<span style=\"color:red\">");
            var startRange = document.createRange();
            startRange.setStart(range.startContainer, range.startOffset);


            var selectionEnd = $("</span>");
            var endRange = document.createRange();
            endRange.setStart(range.endContainer, range.endOffset);

            startRange.insertNode(selectionStart[0]);
            endRange.insertNode(selectionEnd[0]);
        }
    }
    catch (e) {

    }
}

But it is giving DOM exception when I am calling the method. I think that when I am inserting starting span tag in front of the selected text, it is disrupting the DOM structure as there is no end tag at that moment. How to solve this problem?

Edited: There will a highlight button. Selecting the text, if user click on the highlight button, the text color of the selected text will change.

dev_android
  • 8,698
  • 22
  • 91
  • 148

2 Answers2

6

if on select u want to change color use this code.

    ::-moz-selection { color: red;}
    ::selection { color: red; }
Shariq Ansari
  • 3,941
  • 1
  • 27
  • 30
  • It is not on select color change, I want to change the background color permanently, even after deselection. – dev_android May 04 '15 at 05:33
  • 1
    ok, i got it. But it was not mentioned in your post that you need permanent color change. I will provide the exact solution. – Shariq Ansari May 04 '15 at 05:47
1

I know that this is a JS question, but there is a CSS selector which allows you to do this.

::selection {
  color: red;
}

If the browser considers that you've made a choice which is not accessible, it might override your colours. Not everything can be styled in this way, but colours and background colours can.

More information:

clinton3141
  • 4,751
  • 3
  • 33
  • 46