Moshe
Moshe

Reputation: 6991

Change Text Color When a Word is Clicked

I am trying to create an app whereby a user can highlight a particular word when they click (or double click) on that particular word. That is to say, that the user can click on any word in any paragraph in the article in question and highlight it either by changing it's background color or by changing it's font color.

I am having trouble, though, figure out how to do this. I don't want the entire paragraph highlighted and I don't want to have to wrap each word in a unique component or html tag. What I basically want is a wrapping component for the entire article that will note only the particular word being clicked and then allow me to decide what css properties on that word I want to change (such as background color or text color).

But I can't figure out how to do this. Is there a library that already does this. If not, how can I wrap the article as a whole but get access to the singular word that is being clicked?

For what it is worth, I am creating the app using React.

Upvotes: 0

Views: 721

Answers (4)

Moshe
Moshe

Reputation: 6991

For my purposes, the css pseudo-selector ::selection did the job. It allows me to change the background or text color of any word that I click (or any group of words that I highlight).

The only drawback is that it does not allow me to maintain the state of having been clicked -- so that I cannot click on multiple words and have them all have their color changed.

Upvotes: -1

A Haworth
A Haworth

Reputation: 36426

If we take ideas from Detect which word has been clicked on within a text we can replace all instances of a word with the word wrapped in a span to give, for example, highlighting.

This code uses only space as a word delimiter, obviously in production a wider definition of what a word is will need to be used. It also highlights all occurences of a clicked word - not clear whether that is what is required or not - and removes any existing highlighting. Again in production different types of highlighting may be needed depending on the particular word clicked so this is just to get things started:

<head>
<style>
.highlight {
  background-color: yellow;
}
</style>
</head>
<body>
<div class="clickable">
<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,  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,  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.

</p><p>Duis autem vel eum iriure dolor in hendrerit in vulputate velit esse molestie consequat, vel illum dolore eu feugiat nulla facilisis at vero eros et accumsan et iusto odio dignissim qui blandit praesent luptatum zzril delenit augue duis dolore te feugait nulla facilisi. Lorem ipsum dolor sit amet, consectetuer adipiscing elit, sed diam nonummy nibh euismod tincidunt ut laoreet dolore magna aliquam erat volutpat.

Ut wisi enim ad minim veniam, quis nostrud exerci tation ullamcorper suscipit lobortis nisl ut aliquip ex ea commodo consequat. Duis autem vel eum iriure dolor in hendrerit in vulputate velit esse molestie consequat, vel illum dolore eu feugiat nulla facilisis at vero eros et accumsan et iusto odio dignissim qui blandit praesent luptatum zzril delenit augue duis dolore te feugait nulla facilisi.

Nam liber tempor cum soluta nobis eleifend option congue nihil imperdiet doming id quod mazim placerat facer possim assum. Lorem ipsum dolor sit amet, consectetuer adipiscing elit, sed diam nonummy nibh euismod tincidunt ut laoreet dolore magna aliquam erat volutpat. Ut wisi enim ad minim veniam, quis nostrud exerci tation ullamcorper suscipit lobortis nisl ut aliquip ex ea commodo consequat.

</p><p>Duis autem vel eum iriure dolor in hendrerit in vulputate velit esse molestie consequat, vel illum dolore eu feugiat nulla facilisis.
</p>
</div>
<script>
    let clickable = document.querySelector('.clickable');
    
    clickable.addEventListener('click',function (e) {
        
        let sel = window.getSelection();
        let range = sel.getRangeAt(0);
        let node = sel.anchorNode;
        //NOTE at the moment we are only looking at space terminating a word. Need probably to look for all non alphabetic characters (e.g. punctuation)
        while ((range.toString().indexOf(' ') != 0) && (range.startOffset > 0)) { //check we aren't at the start of the clickable element             
            range.setStart(node,(range.startOffset -1));
        }
        range.setStart(node, range.startOffset +1);
         
        do {
           range.setEnd(node,range.endOffset + 1);
        } while(range.toString().indexOf(' ') == -1 && range.toString().trim() != '');
        
        let word = range.toString().trim();
        
        clickeds = clickable.querySelectorAll('.highlight');
        for (let j=0; j < clickeds.length; j++) {
            clickeds[j].outerHTML = clickeds[j].innerHTML;// remove span for hightlighting
        }
        clickable.innerHTML = clickable.innerHTML.replaceAll(word, '<span class="highlight">' + word + '</span>' );
       });

</script>
</body>

Upvotes: 0

i am davood
i am davood

Reputation: 175

you can access to selected text in page with this method:

window.getSelection()

now we can edit any selected text in page , like this :

window.getSelection().anchorNode.parentElement.innerHTML =
window.getSelection().anchorNode.parentElement.innerHTML.replace(
  window.getSelection().toString() ,
    "<b>" +
    window.getSelection().toString() +
    "</b>"
  )

this code make bold the selected text to change color or hightlight you can try this :

  window.getSelection().anchorNode.parentElement.innerHTML =
    window.getSelection().anchorNode.parentElement.innerHTML.replace(
      window.getSelection().toString() ,
        "<span style='color:red;'>" +
        window.getSelection().toString() +
        "</span>"
      )

hope useful :)

Upvotes: 1

Jakub Zavazal
Jakub Zavazal

Reputation: 60

Without using any library, you can go this way and split it by words and apply some styles after click

<html>

<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width">
    <title>Click a word in the paragraph and highlight it.</title>
    <script src="https://code.jquery.com/jquery-git.js"></script>
</head>

<body>
    <p id="paragraph">
        Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.
    </p>
    <script>
        $( document ).ready(
            function() {
                const words = $("#paragraph").first().text().split( /\s+/ );
                const text = words.join( "</span> <span>" );
                $( "#paragraph" ).first().html( "<span>" + text + "</span>" );
                $( "span" ).on( "click", function() {
                $( this ).css( "background-color", "red" );
                });
            }
        )
    </script>
</body>

</html>

Upvotes: 1

Related Questions