Turn off Highlighting on a Website

I conducted an experiment similar to 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>

Upon clicking the 'highlightME' text, all instances of it on the page are highlighted. However, the highlighting remains visible at all times.

I am looking for a way to remove the highlighting by clicking the text again, pressing ESC, or using any other method available.

Any solution involving changes in JavaScript, CSS, or HTML is welcome.

~ thank you.

Answer №1

let isTextHighlighted = false;

clickFunction = function(element) {
        let text = $(element).text();
        searchForText(text);
    }

searchForText = function (textToSearch) {
let color = isTextHighlighted?'transparent':'yellow';
        if (window.find && window.getSelection) {
            document.designMode = "on";

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

Simply add a variable to keep track of whether the text is highlighted or not and set the color variable based on it.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Can JavaScript executed within a web browser have the capability to manipulate files on the underlying host system's file system?

Is it possible to programmatically move files or folders from a website using code? I am aware that with Python and Node.js, this can be achieved through the OS, path, and fs modules. Can JavaScript running in a website also handle file management tasks ...

What is the best way to retrieve a new line from a textarea within a form using PHP?

Is there a way for me to preserve new line formatting when users input text in a textarea within my form and then submit it, so that the displayed text remains unchanged? Just to clarify, I retrieve the variables from the form using the POST method in my ...

The window.addEventListener function is failing to work properly on mobile devices

Hey there! I am facing an issue in my JS code. I wrote this code because I want the menu to close when a visitor clicks on another div (not the menu) if it is open. The code seems to be working fine in developer tools on Chrome or Firefox, but it's no ...

Using a variety of emojis simultaneously on one webpage

Recently, I incorporated the EmojiRating plug-in into my project for jquery emoticon rating. I am attempting to integrate it within an asp:DataList in order for it to repeat for each item. <asp:DataList ID="dtl1" runat="server" DataKeyField="QId" ...

Automatically save user input in form fields with the help of jQuery and AJAX technology

I'm working on a form that has various input fields, and I need the data entered by the user to be automatically stored in the database every minute. After the user submits the request, it will be processed in a struts file where database interactions ...

Switch out the view div element with ui-router

Currently, I am utilizing Angular ui-router to manage various views in the following manner: <div ui-view="header"></div> <div ui-view="nav"></div> <div ui-view></div> Upon Angular loading, the divs are automatically p ...

The logout() function in Passport JS seems to be malfunctioning as it is not being triggered at all

I've been working on adding a logout feature to my app using passport js. So far, I have successfully set up register, login, and session functionalities. However, when I create the logout endpoint and call req.logout(), the function seems to be ignor ...

Tips for replacing spaces with &nbsp; in a string using ReactJS and displaying it in HTML

<div className="mt-2 font-sidebar capitalize"> {item.title} </div> item.title can vary and be any string retrieved from the backend, such as "all products", "most liked", "featured items", etc. I am looking for a solution to subst ...

Eliminate duplicate entries in typeahead.js by ensuring unique data sources for both prefetch and remote

Currently, I have implemented typeahead.js with both prefetch and remote data sources. You can check out the example here. $(document).ready(function() { var castDirectors = new Bloodhound({ datumTokenizer: Bloodhound.tokenizers.obj.whitespace('val ...

Error in background request for Chrome app/extension, or problem allowing app to access Google Docs API

I'm encountering an issue where the Google Doc API is not allowing a desktop application to be installed, although this worked fine in Chrome 27.0 previously. Below is my Manifest.Json file: { "name": "__MSG_extName__", "description": "__MSG_ext ...

Meteor - Utilizing If Statements in HTML Documents

Currently, I am utilizing an FS Collection named "MyUploads" for storing user-uploaded files. Within the HTML structure, there exists a submit button that needs to be displayed conditionally. The question at hand is: how can I create an if statement so tha ...

Creating a delayed queue using RxJS Observables can provide a powerful and

Imagine we have a line of true or false statements (we're not using a complicated data structure because we only want to store the order). Statements can be added to the line at any time and pace. An observer will remove items from this line and make ...

Custom JavaScript clock designed for the Lockscreen of jailbroken iPhones

I am struggling with getting my JavaScript code to display the time correctly on my HTML Lockscreen. After looking at a few examples, I noticed that others are using document.getElementById() instead of document.write() and pushing it to a div. I attempt ...

It's not possible to add additional options to the select input in a react

Hi there! I'm currently facing an issue while trying to retrieve a list of options from the backend, map them to another list of options, and add them to a main list. Unfortunately, my attempts have not been successful. Could anyone offer some advice ...

Tips on managing multiple form data using ajax for php backend

<input type="text" value="2021-05-01" class="date" name="date"> <input type="text" value="10:00" class="starttime" name="starttime"> ...

Activate the stripe button after successful bootstrap validation

My goal was to implement BootstrapValidator for validation on a couple of fields and enable the Stripe button only when both fields are valid. Currently, the button is enabled once any of the fields pass validation. The challenge lies in ensuring that the ...

Angular 12: Running ng test shows code coverage error - TypeError: Unable to access 'initialize' property as undefined

I encountered an error in the code coverage console: TypeError: Cannot read properties of undefined (reading 'initialize') I am trying to call a service method from the component.ts file The code in the component.ts file looks like: this.myAuth ...

"Utilize JavaScript to structure JSON, eliminate redundant entries, and calculate the total number

I'm feeling a bit disoriented, as I have this dataset in json format with timestamps and ids arranged like so: [{ "date":"2016-11-18 19:20:42","id_pa":"7" },{ "date":"2016-11-18 19:04:55","id_pa":"5" },{ "date":"2016-11-19 20:53:42","id_pa":"7" ...

Submitting forms using Jquery Mobile

Hi there! I need some assistance with a form that I have created for use with phonegap. I was initially using JavaScript to process it, but now I'm considering switching to jQuery for better functionality. My main goal is to display the "total" in a n ...

I am having trouble grasping the concept of CSS and the first-child selector

I am having an issue with the first-child selector in CSS. I have two divs with the same class, each containing an image and a paragraph element. When I use the .div-class:first-child {margin:10} rule, the margin is only applied to the paragraph in the fir ...