Respected Members,
I am designing the website in pure HTML with the help of one Template.
In that i have one textbox[search] and Go button.
I want to make operation such that when any one types certain text and presses Go button, It should highlight the text in that website which is matching to that text.
How can i do that?
Than You.
$(document).ready(function(){
$('#searchItem').keyup(function(){
var name = $(this).val();
var pattern = name.toLowerCase();
var targetId = "";
var divs = document.getElementsByClassName("item");
$(document).find('.item').hide();
$('.item').each(function(i){
var para = divs[i].getElementsByTagName("p");
var index = para[0].innerText.toLowerCase().indexOf(pattern);
if (index != -1) {
$(this).show();
}
});
});
});
You didn't posted what you have. I think this is what you are mentioning.
Check this. I can do this for you but you have to do it in your ideas
function highlightInElement(elementId, text){
var elementHtml = document.getElementById(elementId).innerHTML;
var tags = [];
var tagLocations= [];
var htmlTagRegEx = /<{1}\/{0,1}\w+>{1}/;
//Strip the tags from the elementHtml and keep track of them
var htmlTag;
while(htmlTag = elementHtml.match(htmlTagRegEx)){
tagLocations[tagLocations.length] = elementHtml.search(htmlTagRegEx);
tags[tags.length] = htmlTag;
elementHtml = elementHtml.replace(htmlTag, '');
}
//Search for the text in the stripped html
var textLocation = elementHtml.search(text);
if(textLocation){
//Add the highlight
var highlightHTMLStart = '<span class="highlight">';
var highlightHTMLEnd = '</span>';
elementHtml = elementHtml.replace(text, highlightHTMLStart + text + highlightHTMLEnd);
//plug back in the HTML tags
var textEndLocation = textLocation + text.length;
for(i=tagLocations.length-1; i>=0; i--){
var location = tagLocations[i];
if(location > textEndLocation){
location += highlightHTMLStart.length + highlightHTMLEnd.length;
} else if(location > textLocation){
location += highlightHTMLStart.length;
}
elementHtml = elementHtml.substring(0,location) + tags[i] + elementHtml.substring(location);
}
}
//Update the html of the element
document.getElementById(elementId).innerHTML = elementHtml;
}
highlightInElement("fatDoggie","The dog is really really fat");
This fiddle was made to highlight a set of text instead you should get the variable in search and place in the highlightInElement("Element","Var");
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With