An experiment in highlighting words

An experiment in highlighting words using only some CSS and JavaScript

I want to play with the idea of allow people to click on words within a sentence to be able to “highlight” those words. It will be building towards something I am working on that will allow people to have a palette of colours which they can use to signify their feelings towards certain parts of a sentence.

I figure the first thing I want to do is group my words into something and split each word out as a span element. I will also need some CSS to know when I have highlighted a word correctly or not.

<blockquote id="highlightable">
  <span>Here</span> <span>are</span> <span>some</span> <span>words</span> <span>I</span> <span>want</span> <span>to</span> <span>highlight</span>

.highlighted {
  background-color: yellow;

Which makes

Here are some words I want to highlight

Next up I want some JavaScript which recognises that I have clicked on one of these spans;

  function highlightText(event) {
    event.currentTarget.className = (event.currentTarget.className === "highlighted") ? "" : "highlighted";
  var spans = document.getElementById("highlightable").getElementsByTagName("span");
  for(var i = 0; i < spans.length; i++) {
    spans[i].addEventListener("click", highlightText, false);

What we have here is a function called highlightText, this will simply accept an event, and if the target of the event (the element clicked on) has our highlighted class set, we remove it, or else we add it.

We attach this highlightText function to each of the spans within our highlightable area.

And here is it working so far.

Here are some words I want to highlight

In another blog post I will go through some thoughts on how I can make a quick colour selector for this, and also how I would go about counting / grabbing the highlighted words.

I want to eventually be able to say something like; 5 words were highlighted, and these were the words.

Recent posts View all


Iterate over indexed params in Rails

When your API isn't Rails-shaped, sometimes you need to handle input differently

Web Dev Jekyll

Running Jekyll from inside VS Code

How to set up your VS Code to run Jekyll without needing extra extensions