home projects speaker

How to highlight search parameters from Search engines with javascript and prototype.js

I needed some code to help visitors on one of our sites at Aller Internett, to be able to spot the content where the search parameters where mentioned. After some searching and tutorial scavenging, I came up with this script

Table of Contents

  1. Step one: Define searchterms var
  2. Step two: parseReferrer function
  3. Step three: locateSearchTerms function
  4. Step four: highlightSearchTerms function
  5. Step five: Trigger the feature

Add it to the bottom of you page for best practice.

Step one: Define searchterms var

First, we define the searchterm var:

javascript
var searchTerms=null;

Step two: parseReferrer function

Now we want to create a function that parses the search engines query string:

javascript
function parseReferrer(term) {

  var ref = document.referrer.split('?');
  var parms = ref[1].split('&');

  for (var i=0; i < parms.length; i++) {
    var pos = parms[i].indexOf('=');

    if (pos > 0) {
      if(term == parms[i].substring(0,pos)){
        searchTerms  = parms[i].substring(pos+1);
      }
    }
  }
}

Step three: locateSearchTerms function

We need a function that kickstarts the higlight function. We add a loop if the searchterms var contains more than one parameter:

javascript
function locateSearchTerms(){

  terms = searchTerms;

  if (terms.indexOf('+') > -1){
      var parms = terms.split('+');

      for (var i=0; i < parms.length; i++) {
        highlightSearchTerms(parms[i]);
      }
  } else {
    highlightSearchTerms( terms );
  }
}

Step four: highlightSearchTerms function

And now, the function that does the magic. Basically, it locates every string that matches and wraps it with a span tag. It could be simplified, but it works

Important

Remember to make a css class named highlight with the wanted css for the higlights

javascript
function highlightSearchTerms(sword) {

  $('body').map(Element.extend).first().descendants().each(function (el) {
    if (el.nodeType == Node.ELEMENT_NODE && el.tagName != 'TEXTAREA' && el.tagName != 'INPUT' && el.tagName != 'SCRIPT') {
      $A(el.childNodes).each(function (onlyChild) {
        var pos = onlyChild.textContent.indexOf(sword);

        if (onlyChild.nodeType == Node.TEXT_NODE && pos >= 0) {
          var spannode = document.createElement('span');
          spannode.className = 'searchHighlight';
          var middlebit = onlyChild.splitText(pos);
          var endbit = middlebit.splitText(sword.length);
          var middleclone = middlebit.cloneNode(true);
          spannode.appendChild(middleclone);
          middlebit.parentNode.replaceChild(spannode, middlebit);
          onlyChild. = el.innerHTML.replace(new RegExp('('+sword+')', 'gi'), '<span class="highlight">$1</span>');
        }
      });
    }
  });
}

Step five: Trigger the feature

Now that every function that's needed is in place, we need to trigger it when we want to. Basically, it checks if the referrer is a search engine, and sends the correct query var to the parseReferrer function. You can add more search engines yourself, just remember to add the correct var!

javascript
document.observe('dom:loaded', function() {

  if(document.referrer != ''){
    if (document.referrer.indexOf('google.com') > -1){
      searchQueryVar = 'q';
      parseReferrer(searchQueryVar);
      locateSearchTerms();
      } else if (document.referrer.indexOf('yahoo.com') > -1){
        searchQueryVar = 'p';
        parseReferrer(searchQueryVar);
        locateSearchTerms();
      }
  }
});

About the author

Hi! My name is Alexander, and I am a creative frontender, specializing in UX, accessibility, universal design, frontend-architecture, node and design systems. I am passionate with open source projects and love to dabble with new emerging technologies related to frontend. With over 26 years of frontend experience, I have earned the right to be called a veteran. I am a lover of life, technologist at heart. If I am not coding, I am cooking and I love whisky and cigars. Oh, and coffee, I LOVE coffee!

If you want to know more about me, here is some links you might want to check out: GitHub, Instagram, Twitter, LinkedIn, CodePen, Slides.com, npm,

Speaker

I am also an avid speaker on several topics! Check out some of the things I speak about, and contact me if you are interested in having me at your next event!