If you want to mimic the in page search similar to built in browsers, then this will do it!
function in_page_search_shortcode() {
ob_start();
?>
<div id="in-page-search">
<input type="text" id="inPageSearchInput" placeholder="Type to search..." />
</div>
<script>
(function() {
const searchInput = document.getElementById('inPageSearchInput');
const targetContainer = document.querySelector('main') || document.body; // Limit search scope to main content// Function to walk through text nodes and exclude hidden elements
function walkTextNodes(node, callback) {
if (node.nodeType === 3) { // Text node
callback(node);
} else if (node.nodeType === 1) { // Element node
const style = window.getComputedStyle(node);
if (style.display !== 'none' && style.visibility !== 'hidden') {
node.childNodes.forEach(child => walkTextNodes(child, callback));
}
}
}// Function to highlight matches
function highlightMatches(searchText) {
const regex = new RegExp(`(${searchText})`, 'gi');walkTextNodes(targetContainer, (textNode) => {
const parent = textNode.parentNode;
const text = textNode.textContent;if (regex.test(text)) {
const span = document.createElement('span');
span.innerHTML = text.replace(regex, '<mark class="highlight">$1</mark>');
parent.replaceChild(span, textNode);
}
});
}// Function to clear highlights
function clearHighlights() {
const highlightedElements = targetContainer.querySelectorAll('mark.highlight');
highlightedElements.forEach(mark => {
const parent = mark.parentNode;
parent.replaceChild(document.createTextNode(mark.textContent), mark);
parent.normalize(); // Merge adjacent text nodes
});
}// Event listener for input
searchInput.addEventListener('input', function() {
const searchText = this.value.trim();clearHighlights(); // Reset highlights
if (searchText.length > 0) {
highlightMatches(searchText); // Apply new highlights
}
});
})();
</script>
<style>
#in-page-search {
margin-bottom: 20px;
}
#inPageSearchInput {
width: 100%;
padding: 10px;
font-size: 16px;
border: 1px solid #ccc;
border-radius: 5px;
}
mark.highlight {
background-color: yellow;
color: black;
}
</style>
<?php
return ob_get_clean();
}
add_shortcode('in_page_search', 'in_page_search_shortcode');
Shortcode
[in_page_search]