Thursday, April 16, 2009

Highlighting/Toggle Highlighting words on page using javascript

Highlighting/Toggle Highlighting words on page using javascript..

in many site we found that they are highliting words on their page accourding requirement.
once i need to highlight all words on page as hyperlink.I used JQuery and make a function
for that.
This function accept an array of words and highlight all words from array on the page.
JQuery helps me alot to do this with minimum time and efforts.
Belo function will search your words in div,span and p tag,make it hyperlink by replacing word with html.
you can also use this function to toggle highlighting of words in the array.
In shotr this is the function to highlight words on page using javascript.
or function to toggle highlight words on page using javascript.


<script type="text/javascript" language="javascript">
var flag=true;
var inputArray=["haresh","dhameliya"];
function ToggleHighlight()
{
var wordArray=inputArray;
if(flag)
{
$("p,span,div").each(function()
{
var tmpText=$(this).html();
for(var i=0;i<wordArray.length;i++)
{
var sRegExInput;
sRegExInput = new RegExp(wordArray[i], "gi");
tmpText=tmpText.replace(sRegExInput,'<span class="tmp"><a href="#"><b>'+wordArray[i]+'<\/b><\/a></span>');
}
$(this).html(tmpText);
})
}
else
{
for(var i=0;i<wordArray.length;i++)
{
$(".tmp:contains("+wordArray[i]+")").replaceWith(wordArray[i]);
}
}
flag=!flag;
}
</script>


Thank to JQuery.