yifan
yifan

Reputation: 47

Disable Highlighting In A Web Page

I did an experiment like this:

<div onclick="clickfunc(this)"> highlightME </div>
<div> ooo blablabla highlightME ooo highlightME ooo highlightME ooo</div>

<script language=javascript>

    function clickfunc(obj) {
        var t = $(obj).text();
        doSearch(t);
    }

    function doSearch(text) {
        if (window.find && window.getSelection) {
            document.designMode = "on";
            // var sel = window.getSelection();
            // console.log(sel);
            // sel.collapse(document.body, 0);

            while (window.find(text)) {
                document.execCommand("HiliteColor", false, "yellow");
                //sel.collapseToEnd();
            }
            document.designMode = "off";
        }
        else if (document.body.createTextRange) {
            var textRange = document.body.createTextRange();
            while (textRange.findText(text)) {
                textRange.execCommand("BackColor", false, "yellow");
                textRange.collapse(false);
            }
        }
    }
</script>

When I click the text 'highlightME', it will highlight all occurrences on the page. However, the highlight will be always there.

I want to remove the highlighting by clicking second time on the text, or press ESC or via any other ways.

Doesn't matter if it requires either js, css or html changes.

~ thanks.

Upvotes: 3

Views: 318

Answers (1)

Jared Chu
Jared Chu

Reputation: 2862

var isHighLighting = false;

clickfunc = function(obj) {
        var t = $(obj).text();
        doSearch(t);
    }

doSearch = function (text) {
var color = isHighLighting?'transparent':'yellow';
        if (window.find && window.getSelection) {
            document.designMode = "on";
            // var sel = window.getSelection();
            // console.log(sel);
            // sel.collapse(document.body, 0);

            while (window.find(text)) {
                document.execCommand("HiliteColor", false, color);
                //sel.collapseToEnd();
            }
            document.designMode = "off";
        }
        else if (document.body.createTextRange) {
            var textRange = document.body.createTextRange();
            while (textRange.findText(text)) {
                textRange.execCommand("BackColor", false, color);
                textRange.collapse(false);
            }
        }
        isHighLighting = !isHighLighting;
    }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<div onclick="clickfunc(this)"> highlightME </div>
<div> ooo blablabla highlightME ooo highlightME ooo highlightME ooo</div>

Just add a variable to check is text highlighting or not and set color variable base on it.

Upvotes: 1

Related Questions