code everywhere

Sentence Highlighting with javascript

posted on December 2, 2016, 12:00 am in js

Readability is important when writing articles. More than good design, there are other ways to make the experience better. One of those ways is to highlight sentences so text is easier to follow.

Heres some Javascript code that will add sentence highlighting to your text so users can follow along as they read. Insert the code, change the targetClass to the class you want to apply, add some CSS for span.highlight:hover {} and you're done.

span.highlight {
    
transition300ms ease-in-out;
}
span.highlight:hover {
    
background#e8e8e8;
}
var targetClass "body";
    var 
elems document.getElementsByClassName(targetClass)[0].innerHTML;
    
// find text within tags
    
var regex = new RegExp('>(.+)</''gi');
    var 
matches elems.matchregex );
    
// Loop matches
    
matches.forEach(function(valiarr) {
        
val val.slice(1, -2);
        
val val.split(/[\.!]\s/);
        
val.forEach(function(item) {
            if( 
item.length 20 )        // Sentences longer than 20
                
elems elems.replace(item'<span class="highlight">' item "</span>");
        });
    });
    
// Write back to document
    
document.getElementsByClassName(targetClass)[0].innerHTML elems;

You can add the code above inside a

document.addEventListener("DOMContentLoaded", function() { ... });

to ensure it loads after the content.

recent posts

< back
find something helpful? send us some coin BTC 19u6CWTxH4cH9V2yTfAemA7gmmh7rANgiv

(ad) Need Hosting? Try Linode, VPS Starting from $5

privacy policy