0

Select the text and click a button will highlight the text. But if the text is already highlighted, on clicking the button, selected text should become normal.

Is thier a way to do that using Jquery and single button.

Is it possible to findout CSS that is applied to the selected text.

HarshM
  • 21
  • 6

2 Answers2

0

One way is to wrap the selected text in a span with an highlighted class for example.

This answer could be helpful!

How to highlight text using javascript

Tomma5o
  • 57
  • 1
  • 5
0

This has already been answered in this post.

function makeEditableAndHighlight(colour) {
    var range, sel = window.getSelection();
    if (sel.rangeCount && sel.getRangeAt) {
        range = sel.getRangeAt(0);
    }
    document.designMode = "on";
    if (range) {
        sel.removeAllRanges();
        sel.addRange(range);
    }
    // Use HiliteColor since some browsers apply BackColor to the whole block
    if (!document.execCommand("HiliteColor", false, colour)) {
        document.execCommand("BackColor", false, colour);
    }
    document.designMode = "off";
}

function highlight(colour) {
    var range, sel;
    if (window.getSelection) {
        // IE9 and non-IE
        try {
            if (!document.execCommand("BackColor", false, colour)) {
                makeEditableAndHighlight(colour);
            }
        } catch (ex) {
            makeEditableAndHighlight(colour)
        }
    } else if (document.selection && document.selection.createRange) {
        // IE <= 8 case
        range = document.selection.createRange();
        range.execCommand("BackColor", false, colour);
    }
}

document.getElementsByTagName('button')[0].addEventListener('click', function(){
 highlight('red');
});
<div>
  <p>
    Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At vero eos et accusam et justo duo dolores et ea rebum. Stet clita kasd gubergren, no sea takimata sanctus est Lorem ipsum dolor sit amet. Lorem ipsum dolor sit amet, consetetur sadipscing elitr.
  </p>
  <button>Change color</button>
</div>
Schabbi
  • 131
  • 6