Search code examples
javascripthtmlstringhighlighting

Highlight each word on a webpage, one at a time, with JavaScript


What's the best way to visually highlight each word on the page, one at a time? I figure that the words should be broken up into an array and iterated over that way, but what's the best way to do so?

I already know how to perform string replacements and style individual elements, the trick is to do this on each word on the page, one at a time, in the most efficient manner.


Solution

  • Here is my working but unrefined code that achieves highlighting each word one at a time as well as scrolling when the last word in each line is reached:

        <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
        <html xmlns="http://www.w3.org/1999/xhtml">
        <head>
        <meta http-equiv="Content-Type" content="text/html;charset=utf-8"/>
        <title></title>
        <style type="text/css">
        span.highlight {background-color:red;}
        </style>
        <script>
        var height;
        var width;
        var spans = document.getElementsByTagName("span");
        var i = 0;
        var timePerChar = 100;
    
        function getPositionOfElement(el) {
            var elw =  el.offsetWidth;
            var elh =  el.offsetHeight;
            // yay readability
            for (var lx=0, ly=0;
                 el != null;
                 lx += el.offsetLeft, ly += el.offsetTop, el = el.offsetParent);
            return {x: lx,y: ly,w: elw, h: elh};
        }
    
        function highlightElements() {
            //alert(spans[i].innerHTML.length);
            var highlightSpeed = timePerChar * spans[i].innerHTML.length;
            spans[i].setAttribute("class", "highlight");
            var objInfo = new Object();
            var nxtObjInfo = new Object();
            objInfo = getPositionOfElement(spans[i]);
            nxtObjInfo = getPositionOfElement(spans[i+1]);
            var amt = (objInfo.x + objInfo.w + 50);
            console.log(amt);
            console.log(width);
            if(amt >= width && objInfo.x > nxtObjInfo.x){
                console.log('SCROLL ' +objInfo.h+ ' ');
                window.scrollBy(0,objInfo.h);
            }
            setTimeout('unHighlight()', highlightSpeed);
        }
    
        function unHighlight (){
            spans[i].removeAttribute("class");
            i++;
            if(i < spans.length) {
                highlightElements();
            }
        }
    
        // This is just a namespace 
        var CIRRO = function(){ 
         return { 
          /** 
           * Initialize the page behaviors 
           */ 
          init : function() { 
           CIRRO.wrapWordsWithSpan(); 
          },   
          /** 
           * Replace the contents of each paragraph with span wrapped words 
           */ 
          wrapWordsWithSpan : function() { 
           var paragraphs = document.getElementsByTagName("p");
           //alert(paragraphs.length);
           if(!paragraphs ) return; 
           var j = 0;
           while(j < paragraphs.length) {
                // Parse the text into an array 
               var arr = paragraphs[j].innerHTML.split(" "); 
               // Generate span's for each item/word in the array 
               for( var i = 0; i < arr.length; i++ ) { 
                arr[i] = "<span>" + arr[i] + "</span>"; 
               }    
               paragraphs[j].innerHTML = arr.join(" "); 
               //alert(paragraphs[j].innerHTML); 
               j++
           }
          } 
         }; 
        }(); 
        window.onload = CIRRO.init; 
        </script>
        </head>
        <body id="body">
        <input type="button" onclick="highlightElements();" value="Get selected elements" />
        <p>Test test test test test Test test test test test Test test test test test Test 
    test test test test Test test test test test Test test test test test Test test test test 
    test Test test test test test Test test test test test Test test test test test Test test 
    test test test Test test test test test Test test test test test Test test test test test 
    Test test test test test Test test test test test Test test test test test Test test test 
    test test</p>
        <script>
        var test = document.getElementById("body");
        height = (test.clientHeight + 1);
        width = (test.clientWidth + 1);
        //alert(width +' '+ height);
        </script>
        </body>
    
    </html>