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
- Step one: Define searchterms var
- Step two: parseReferrer function
- Step three: locateSearchTerms function
- Step four: highlightSearchTerms function
- 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:
Step two: parseReferrer function
Now we want to create a function that parses the search engines query string:
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:
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
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!