My client wants to add a search box on specific pages that will allow their user to search for a question and it will scroll to that text. This way it’s easier for him to direct clients to the right part of the FAQ question.
After searching keyword "order", the function scrolls and highlights "order" on page, but the dropdown stops working and we have to refresh the page to start searching from the beginning.
I am looking for a function in which it scrolls smoothly and don’t have to refresh the page to search another keyword.
Any advice on how to accomplish this?
<input type="text" id="search-term" />
<input type="submit" id="search-button" value="search" />
function searchAndHighlight(searchTerm, selector) {
if(searchTerm) {
// var wholeWordOnly = new RegExp("\g"+searchTerm+"\g","ig"); //matches whole word only
//var anyCharacter = new RegExp("\g["+searchTerm+"]\g","ig"); //matches any word with any of search chars characters
var selector = selector || ".faq" ; //use body as selector if none provided
var searchTermRegEx = new RegExp(searchTerm,"ig");
var matches = $(selector).text().match(searchTermRegEx);
if(matches) {
$('.highlighted').removeClass('highlighted'); //Remove old search highlights
$(selector).html($(selector).html()
.replace(searchTermRegEx, "<span class='highlighted'>"+searchTerm+"</span>"));
if($('.highlighted:first').length) { //if match found, scroll to where the first one appears
$(window).scrollTop($('.highlighted:first').offset().top);
}
return true;
}
}
return false;
}
$(document).ready(function() {
$('#search-button').on("click",function() {
if(!searchAndHighlight($('#search-term').val())) {
alert("No results found");
}
});
});
2
Answers
This worked for me:
Your fixed script is here; Hope to be useful: