Add Search Keyword Highlighting to Any Webpage with Mark.js

Most browsers have the CTRL+F functionality to search and find whatever the user is looking for. But, this feature isn’t supported on mobile devices and it doesn’t work well using dynamic text.

Luckily, there’s Mark.js, a free JavaScript plugin that adds a highlight search feature to any page with ease.

By default, it works as a vanilla JS plugin but can also run on top of jQuery. It’s a completely open-source project, so you’re free to use this on any website commercial or otherwise.

It works much like any browser search feature, except it comes with extra goodies. You can add your own custom filters and search for words based on regular expressions, specific synonyms, and even in dynamic page elements such as iframes.

To get started, just download the Mark.js file from GitHub or host the file through a CDN to save time.

You should run this function connected to an input field on the page. This way users can enter search terms and get immediate feedback via highlighted text.

Here’s a sample snippet from the demo page:

$(".context").mark(keyword [, options]);

The .context class targets wherever the function should search for terms. You might use the default HTML <body> element if you’re trying to search the entire page, or you could pass multiple elements such as different tabbed widgets or iframes.

Then, inside the mark() function you pass the keyword, along with the options (if you wish).

If you let users type in a keyword then you can auto-update the function with a new keyword after every keypress. There’s even a specific function to target this event.

Mark.js works with all major browsers, including Chrome, Firefox, Opera (v12+), and Internet Explorer (9+). It’s real easy to set up if you follow the docs and use the newest files.

But, if you want to see Mark.js in action take a peek at the fiddle below using a very basic jQuery demo to search a few paragraphs of Lorem Ipsum.