JavaScript Search Text on Page and Highlight

JavaScript Search Text on Page and Highlight
Code Snippet:Search and highlight: Real-time search and highlighting
Author: Ian Johnson
Published: January 10, 2024
Last Updated: January 22, 2024
Downloads: 797
License: MIT
Edit Code online: View on CodePen
Read More

The JavaScript code snippet helps you to search for text on a web page and highlight the matching text. It searches for a specified text input and then highlights the matching results on the page. This functionality is helpful for users who want to quickly find and visually identify specific text content within a webpage.

It enhances the accessibility and usability of your site, especially for longer documents or content-heavy pages.

How to Search Text On Page and Highlight Using JavaScript

1. First, make sure your website’s HTML structure includes the necessary elements. In the following code, a search input field, a clear button, and content items are enclosed within a <section> element. Ensure your HTML is organized similarly.

<section search="container">
    <h1>Search and highlight</h1>

    <form class="input__container">
      <input type="text" search="input" placeholder="Search Miguel or Charles">
      <button type="reset" title="Clear input" search="clear" hidden>
        <svg viewBox="0 0 20 20">
          <path
            d="M11.4142136,10 L14.2426407,7.17157288 L12.8284271,5.75735931 L10,8.58578644 L7.17157288,5.75735931 L5.75735931,7.17157288 L8.58578644,10 L5.75735931,12.8284271 L7.17157288,14.2426407 L10,11.4142136 L12.8284271,14.2426407 L14.2426407,12.8284271 L11.4142136,10 L11.4142136,10 Z M2.92893219,17.0710678 C6.83417511,20.9763107 13.1658249,20.9763107 17.0710678,17.0710678 C20.9763107,13.1658249 20.9763107,6.83417511 17.0710678,2.92893219 C13.1658249,-0.976310729 6.83417511,-0.976310729 2.92893219,2.92893219 C-0.976310729,6.83417511 -0.976310729,13.1658249 2.92893219,17.0710678 L2.92893219,17.0710678 Z M4.34314575,15.6568542 C7.46734008,18.7810486 12.5326599,18.7810486 15.6568542,15.6568542 C18.7810486,12.5326599 18.7810486,7.46734008 15.6568542,4.34314575 C12.5326599,1.21895142 7.46734008,1.21895142 4.34314575,4.34314575 C1.21895142,7.46734008 1.21895142,12.5326599 4.34314575,15.6568542 L4.34314575,15.6568542 Z"
            stroke="none" stroke-width="1" fill="#38383a" fill-rule="evenodd"></path>
        </svg>
      </button>
      <div search="counter"></div>
    </form>

    <details search="item">
      <summary>Don Quixote</summary>
      
      The Ingenious Gentleman Don Quixote of La Mancha, or just Don Quixote, is a Spanish novel by Miguel de Cervantes.
    </details>

    <details search="item">
      <summary>A Tale of Two Cities</summary>
      
      A Tale of Two Cities is an 1859 historical novel by Charles Dickens, set in London and Paris before and during the French Revolution.
    </details>

    <div search="noResults" hidden>No results</div>

  </section>

2. Now, use the following CSS code to style the basic interface for the search. You can customize this CSS to match your website’s theme. Adjust fonts, colors, and sizes to fit your design preferences.

html {
  font-size: 18px;
  background-color: #ebeef3;
  box-sizing: border-box;
  font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, Oxygen, Ubuntu, Cantarell, "Open Sans", "Helvetica Neue", sans-serif;
  color: #38383a;
}

body {
  display: flex;
  padding: 0 1rem;
}

html,
body {
  height: 100%;
  margin: 0;
}

section {
  width: 375px;
  margin: auto;
  padding: 2rem;
  background: white;
  border-radius: 32px;
  box-shadow: 0px 16px 64px -24px rgba(0, 0, 0, 0.45);
}

.input__container {
  position: relative;
}

input {
  font-size: 16px;
  width: 100%;
  padding: 0.75rem;
  border: 2px solid #ebeef3;
  border-radius: 8px;
  box-sizing: border-box;
}

::placeholder {
  opacity: 0.5;
}

details {
  margin-top: 2rem;
  padding-left: 1.35rem;
}
details[open] {
  animation: opacity 0.4s cubic-bezier(0.5, 0, 0.2, 1);
}

summary {
  margin-left: -1.1rem;
  padding-bottom: 0.5rem;
  font-weight: 600;
}

[search=clear] {
  position: absolute;
  right: 0.75rem;
  top: 0.75rem;
  background: none;
  border: none;
  padding: 0;
}
[search=clear] svg {
  height: 24px;
  width: 24px;
  pointer-events: none;
  animation: opacity 0.4s cubic-bezier(0.5, 0, 0.2, 1);
}

[search=counter] {
  position: absolute;
  bottom: -1rem;
  font-size: 0.75rem;
  opacity: 0.5;
}

[search=noResults] {
  margin: 2rem 0 0;
  animation: opacity 0.4s cubic-bezier(0.5, 0, 0.2, 1);
}

@keyframes opacity {
  0% {
    opacity: 0;
  }
  100% {
    opacity: 1;
  }
}

3. Insert the following JavaScript code into your website. It handles the search and highlight functionality. It selects the search input, content items, and other elements to enable searching and highlighting. Ensure the code is placed before the closing </body> tag in your HTML document.

(function () {
  'use strict';

  var controls = {
    input: document.querySelector('[search="input"]'),
    items: document.querySelectorAll('[search="item"]'),
    noResults: document.querySelector('[search="noResults"]'),
    clear: document.querySelector('[search="clear"]'),
    counter: document.querySelector('[search="counter"]'),
    indexedItems: [],
    hasControls: function() {
      return this.input != undefined && this.items != undefined
    }
  }

  // checks for required search components
  if (!controls.hasControls()) return;

  // shows/hides no results message
  function toggleNoResultsMessage(searchTerm) {
    // checks if any items are open
    var hasResults = Array.prototype.filter.call(controls.items, function (item) {
      return item.hasAttribute('open');
    })

    if (hasResults.length && searchTerm.length > 1) {
      // hide no results message if items are open
      controls.noResults.setAttribute('hidden', '');
    } else if (searchTerm.length > 1) {
      // show no results message
      controls.noResults.removeAttribute('hidden');
      Array.prototype.forEach.call(controls.items, function (item) {
        item.setAttribute('hidden', '')
      })
      return;
    } else {
      // hide no results message
      controls.noResults.setAttribute('hidden', '');
    }
  }

  // searches and highlights
  function searchAndHighlight() {
    Array.prototype.forEach.call(controls.items, function (item) {
      item.innerHTML = item.innerHTML.replace(/<mark>([^<]+)<\/mark>/gi, '$1');
    });

    var searchTerm = event.target.value.trim().toLowerCase();

    if (searchTerm.length > 1) {
      controls.indexedItems.forEach(function (item, i) {
        if (controls.indexedItems[i].indexOf(searchTerm) != -1) {
          controls.items[i].setAttribute('open', true);
          controls.items[i].removeAttribute('hidden'); // removes hidden attribute when deleteing
          controls.items[i].innerHTML = controls.items[i].innerHTML.replace(new RegExp(searchTerm + '(?!([^<]+)?>)', 'gi'), '<mark>$&</mark>');
        } else {
          controls.items[i].removeAttribute('open');
          controls.items[i].setAttribute('hidden', '');
        }
      });
      controls.clear.removeAttribute('hidden');
    } else {
      Array.prototype.forEach.call(controls.items, function (item) {
        item.removeAttribute('open');
        item.removeAttribute('hidden');
      });
      controls.clear.setAttribute('hidden', '');
    }
    countHighlights();
    toggleNoResultsMessage(searchTerm);
  }

  // counts number of matches
  function countHighlights() {
    var count = document.querySelectorAll('mark').length;
    if (count) {
      return controls.counter.innerHTML = count + ' results';
    }
    return controls.counter.innerHTML = '';
  }

  // sanitize search result matches
  Array.prototype.forEach.call(controls.items, function (item) {
    controls.indexedItems.push(item.textContent.replace(/\s{2,}/g, ' ').toLowerCase());
  });
  
  controls.input.addEventListener('keydown', function(event) {
    // prevent submit on enter
    if (event.keyCode === 13) 
    {
      event.preventDefault();
      return false;
    }
  })

  // input keyup
  controls.input.addEventListener('keyup', function(event) {
    searchAndHighlight();
  });

  // clear button click
  controls.clear.addEventListener('click', function() {
    event.target.setAttribute('hidden', '');
    toggleNoResultsMessage('');
    searchAndHighlight();
    controls.input.focus();
  })

})();

That’s it! hopefully, you’ve successfully added a text search and highlight feature using JavaScript to your web page. This functionality improves the user experience by making it easier for visitors to find specific content. If you have any questions or suggestions, feel free to comment below.

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.

About CodeHim

Free Web Design Code & Scripts - CodeHim is one of the BEST developer websites that provide web designers and developers with a simple way to preview and download a variety of free code & scripts. All codes published on CodeHim are open source, distributed under OSD-compliant license which grants all the rights to use, study, change and share the software in modified and unmodified form. Before publishing, we test and review each code snippet to avoid errors, but we cannot warrant the full correctness of all content. All trademarks, trade names, logos, and icons are the property of their respective owners... find out more...

Please Rel0ad/PressF5 this page if you can't click the download/preview link

X