How to Highlight Searched Text in a Blogger Post

Insert the following HTML code right after the <body> tag in your Blogger theme.

<!-- To highlight searched text -->
<div id='post-search' style='max-width: 80vw;margin: auto;padding: 6px;background: #030c26;position: sticky;top: 0;z-index: 2;'>
	<input class='searched-text-highlight' id='search-input' placeholder='Search...' style='cursor: auto;' type='text'/>
	<button class='searched-text-highlight' onclick='searchInPost()'>Search</button>
	<button class='searched-text-highlight' onclick='previousMatch()'>&#8592; Previous</button>
        <button class='searched-text-highlight' onclick='nextMatch()'>Next &#8594;</button>
</div>


Insert the following CSS code right before the closing tag in your Blogger theme.

<style>
.searched-text-highlight {
  font-size: 14px;
  border-radius: 6px;
  padding: 3px;
  cursor: pointer;
}

.highlight-text {
      background-color: yellow;
      color: black;
      font-weight: bold;
      padding: 0 2px;
      border-radius: 2px;
}

.highlight-text.active {
      background-color: orange;
}
</style>


Paste the following JavaScript code right before the closing </script> tag in your Blogger theme.

<script>
  let currentMatchIndex = -1; // Track the current match
  let allMatches = []; // Store all highlighted matches

  function searchInPost() {
      const searchInput = document.getElementById("search-input");
      const searchTerm = searchInput.value.trim();

      if (!searchTerm) {
          alert("Please enter a search term.");
          return;
      }

      // Reset previous highlights
      resetHighlights();

      // Get the post content container
      const postContent = document.querySelector(".post-body"); // Adjust selector based on your theme
      if (!postContent) return;

      // Find and highlight matches
      const regex = new RegExp(`(${searchTerm})`, "gi");
      const walker = document.createTreeWalker(postContent, NodeFilter.SHOW_TEXT);
      const nodes = [];

      while (walker.nextNode()) {
          nodes.push(walker.currentNode);
      }

      allMatches = [];
      nodes.forEach(node => {
          const parent = node.parentNode;

          // Skip script, style, and certain elements
          if (["SCRIPT", "STYLE", "NOSCRIPT"].includes(parent.tagName)) return;

          const text = node.nodeValue;
          if (regex.test(text)) {
              const span = document.createElement("span");
              span.className = "highlight";
              span.innerHTML = text.replace(regex, `<span class="highlight-text">$1</span>`);
              parent.replaceChild(span, node);

              // Collect matches
              span.querySelectorAll(".highlight-text").forEach(match => allMatches.push(match));
          }
      });

      if (allMatches.length === 0) {
          alert("No matches found.");
          return;
      }

      currentMatchIndex = 0;
      scrollToMatch();
  }

  function resetHighlights() {
      // Remove all highlights and reset matches
      const highlightedElements = document.querySelectorAll(".highlight");
      highlightedElements.forEach(el => {
          el.outerHTML = el.innerHTML; // Replace span with original text
      });

      allMatches = [];
      currentMatchIndex = -1;
  }

  function scrollToMatch() {
      if (currentMatchIndex &lt; 0 || currentMatchIndex >= allMatches.length) return;

      // Scroll to the current match
      const currentMatch = allMatches[currentMatchIndex];
      currentMatch.scrollIntoView({ behavior: "smooth", block: "center" });

      // Highlight the current match
      allMatches.forEach((match, index) => {
          match.style.backgroundColor = index === currentMatchIndex ? "orange" : "yellow";
      });
  }

  function previousMatch() {
      if (allMatches.length === 0) {
          alert("No matches to navigate.");
          return;
      }

      currentMatchIndex = (currentMatchIndex - 1 + allMatches.length) % allMatches.length;
      scrollToMatch();
  }

  function nextMatch() {
      if (allMatches.length === 0) {
          alert("No matches to navigate.");
          return;
      }

      currentMatchIndex = (currentMatchIndex + 1) % allMatches.length;
      scrollToMatch();
  }
</script>


Post a Comment

0 Comments