Sunday, March 29, 2015

Highlight search text using Java Script

How to  highlight your search results instantly from your web page. As its more like searching an element or a phrase of word in your page or selected section. We will use Java Script to do this. Lets do how to do this.

Open any of those text editor you used. Write down your code or html to design your text portion in your page. Then come to the Java Script portion. Its playing the main role along with css.

As text I am putting the content of Kolkata, my city. You put your content or fetch back from your database. So you can test your application is running successfully or not.

<div id="search" name="search">
    <input name="query" id="query" type="text" size="30" maxlength="30" />
    <input name="searchit" type="button" value="Search" onclick="highlightSearch()" />
    <div id="searchtext">
                Kolkata /koʊlˈkɑːtɑː/, formerly Calcutta /kælˈkʌtə/, is the capital of    the Indian state of West Bengal.
                Located on the east bank of the Hooghly river, it is the principal commercial, cultural,
                and educational centre of East India, while the Port of Kolkata is India's oldest operating
                port as well as its sole major riverine port. As of 2011, the city had 4.5 million residents;
                the urban agglomeration, which comprises the city and its suburbs, was home to approximately
                14.1 million, making it the third-most populous metropolitan area in India. As of 2008,
                its economic output as measured by gross domestic product ranked third among South Asian cities, behind Mumbai and Delhi.


Now write down this java script function to do the trick.

function highlightSearch() {
      var text = document.getElementById("query").value;
      var query = new RegExp("(\\b" + text + "\\b)", "gim");
      var e = document.getElementById("searchtext").innerHTML;
      var enew = e.replace(/(<span>|<\/span>)/igm, "");
      document.getElementById("searchtext").innerHTML = enew;
      var newe = enew.replace(query, "<span>$1</span>");
      document.getElementById("searchtext").innerHTML = newe;

Now you must remember the importance of css to modify the text. So here is the css part to make the text highlighted.

#searchtext span {
    background-color: #FF9;
    color: #555;

div {
  padding: 10px;

Now run your program and test it. Enjoy..
Download the full source code here.


Post a Comment

Popular Posts