1,627 articles and 11,810 comments as of Tuesday, July 13th, 2010

Monday, November 17, 2008

“Search on this Page” using jQuery

jQueryThis article by guest author Waldek Mastykarz, describes how to use the free javascript library, jQuery, to create specialized search capabilities on large web pages.

A followup article will demonstrate how to implement Waldek’s solution in SharePoint using a SharePoint library and the Content Editor Web Part.

Overview

Every modern browser provides the ability to search for text within a page. In most cases that functionality is underserved and allows you to find only one instance of the text at a time.

Google Chrome recently presented improved version of search which searches for the given text as you type and highlights all instances found on the current page. But wait a minute: is this functionality limited to Google Chrome only?

The case

In cases where your pages contain large amounts of text, using search to find a particular piece of text might be very useful and help your users get more productive. By highlighting all found instances you make it easier to find the sought after term and the surrounding fragments which might add some relevant context information.

The search functionality provided by the web browsers doesn’t know anything about how your website is built. Because it lacks that extra piece of information, it searches for the given text within the whole page instead of the container with the most relevant text. Especially in the case of Intranet Applications, it would increase the productivity of the users if they could search only within the boundaries of the main content wrapper.

JQuery

Alt text: Searching in Internet Explorer (IE) 7: IE7 doesn’t provide find-as-you-type functionality and highlights only one match at a time

JQuery

Alt text: Searching in Firefox 3: while it is possible to enable the find-as-you-type functionality Firefox highlights just like Internet Explorer only one match at a time

JQuery

Alt text: Google Chrome provides by default search-as-you-type and also highlights all occurrences of the sought text. The downside is that you cannot limit the search to a particular region of the page

The requirements

The search should be fired as the user types. To prevent the search from showing too many hits, it should be possible to set the minimal length of the sought text. It should be possible to define a region on the page which contains the most important content, providin only the most relevant results. Last, to keep the functionality reusable across different solutions, it should be unobtrusive.

The solution

JQuery

Alt text: Search on this page using jQuery. Found occurrences of the sought text are being highlighted

See it working

In the solution above I have chosen for a fully client-side technology approach. It fulfills all requirements and doesn’t introduce any overhead by making calls to logic available on the server. The downside of such approach is dependency on JavaScript – which is an optional technology and can be disabled by the end users. Because we wanted to keep the functionality unobtrusive, the search box will appear only if the JavaScript is enabled, so that users will never face a half-working functionality.

I have based the solution on the jQuery library. It’s lightweight, it contains all the components required to make it all working and allows you to focus on the solution itself rather than reinventing the wheel and approaching the JavaScript as we would back in the 90’s.

Resources for this solutions:
jQuery Web Site
jQuery Download

How is it made?

There are only two things required to make it all work: creating a new instance of the Imtech.SearchOnThisPage class and calling the init() function:

JQuery

Alt text: Code for instantiating the search component in JavaScript

It’s wrapped in the jQuery ready function because you don’t want to instantiate it before the page has been loaded.

In the situation described above you would use the default settings, for example searching for text which contains at least 3 characters. You can modify the default values by setting the parameters just before calling the init() function:

JQuery

Alt text: Configuring the different parameters of the search component

In the example above we override the default setting and tell the search component to look for strings that contain at least two characters.

The available properties can be found in the script itself:

JQuery

Alt text: Available properties of the search component which can be configured

Because the script filters the user input it is possible to search for a string no matter what the applied HTML formatting might be:

JQuery

Alt text: Search component properly highlights found text no matter the applied HTML formatting

Still, remember one of the requirements is to limit the search to the particular region of the page only? Check it out:

JQuery

Alt text: Search component doesn’t highlight the text which is located outside the given search boundary

Searching for Imtech doesn’t return anything because it is outside the content region we specified while initiating the search component:

JQuery

Alt text: HTML source of text outside the search boundary

JQuery

Alt text: The textWrapper property describes the HTML container which contains the text to search in

Alternatives?

Another plausible approach to fulfill all requirements and provide a similar functionality would be using server-side programming to select the text and AJAX to keep it all from reloading the page each time you type something in. Although it would work, this approach would require custom development, introduce some extra complexity, and would still depend on optional JavaScript technology.

Using a fully client-side approach is probably the most efficient way to provide custom search-as-you-type functionality.

What’s next?

The presented case is quite simple but should give you the idea of what you could achieve with it though. While I have used full-text search as an example, you could make the same script search through the facebook of your organization or a catalog of the products you sell. The script I have created is customizable and can be easily extended to suit your situation.

Coming next: How to implement the jQuery solution in SharePoint.

Waldek MastykarzWaldek Mastykarz
Innovation Matters

Waldek Mastykarz is a software developer living in Alphen aan den Rijn in the Netherlands.

 

Please Join the Discussion

19 Responses to ““Search on this Page” using jQuery”
  1. Chris steel says:

    Nice! One question; this will not take any letters more than A-Z, if i want to include for example nordic letters, å,ä and ö – do you know how? ps, where can i find the original plugin at the jQuery?

  2. Chris Blocher says:

    Is there a way to extend the search to more than one term? Or to content that isn’t embedded in the web part?

  3. Ben says:

    I found a bug!

    Using internet explorer 6, I searched for ‘odio’ which works fine, it highlights the bolded text. But when you add a full-stop / period to the end – ‘odio.’ then the formatting of the page changes! You get this;

    Cras odio. Integer placerat jus….

    What’s going on?!

  4. Ben says:

    ok, my above post has absorbed the html tag that is shown when searching for ‘odio.’

    what you will see is a closing ’strong’ tag.

  5. larry says:

    Is the source code still available to view or download

  6. Larry – For Weekly Newsletter subscribers, the Subscriber Only Archive contains all the downloads. — Mark

  7. dana says:

    1. is it possible to highlight more than one word at a time?

    2. Is it possible to highlight based on words that are not visible.
    For example if a user typed in “architecture’ to the search box, then 4 or 5 items would be highlighted?

    I have target words for each highlightable element, is it possible to include these target words in the search?

    Thank you

    Dana

  8. dana says:

    Is it possible to assign multiple target (invisible) search terms to
    the final highlighted outcome?

    For example if i were to type in architecture, multiple items will be highlighted in addition to architecture.

    Thank you

    Dana

  9. Hi,
    I tried to recreate the example but I can not run anything. I recived am error: Microsoft JScript runtime error: ‘Imtech’ is undefined.
    Does anyone know why is that ?

    Thank you.

  10. Trey says:

    Did anyone check Dana’s request? Any thoughts on it? I’m thinking of making custom arrays and connecting the selector from the query. Thoughts?

  11. Joyce says:

    This is great!

    One problem: is there a way to make this NOT search within tag contents? For example, I have images with width and height attributes specified within the img tag. If I search the word “width,” suddenly the contents of the img tag appear visible on the page next to the image and the width attribute name is highlighted. If I search a word in the alt text of an image, the image blows up to be enormous and the alt tag text appears, highlighted. This is rather inconvenient. It’s great that it works for text enclosed in closing and end tags in the #body (as shown in the “cras” example above), but is there any way to discount text within the actual element tags?

    Thanks! Joyce

  12. Siddharth Roy says:

    Hi,

    Is there a way to execute a SQL Query (which has a variable input)in a SharePoint site such that when users type anything in a textbox, that value is taken as input for the sql query.

    I want to do it without server-side coding? Any OOTB method???

    Thanks,
    Sid

  13. AJ says:

    Has anyone managed to figure out how to exclude element tags? Joyce had this problem back in May last year and I was just wondering if anyone had managed to find a workaround.

    This is a lovely concept, but I am having the same problem where my implementation of the above code is displaying ‘class’ tags and showing text from URIs.

  14. AJ says:

    You can see the problem using your example by typing in “str” or even “/.”. I thought I had found a fix by adding the code below:

    var i = -1;
    i = text.indexOf(searchText, i+1);
    if (text.lastIndexOf(">", i) >= text.lastIndexOf("<", i)) {
      text = text.replace(regx, '$1');
      $(this).html(text);
    }
    

    This isn’t a good enough solution as it doesn’t apply the background to any ‘on screen’ text that matches any html element names.

    Has anyone come up with a suitably robust application of this concept using jQuery?

  15. Michael says:

    Great Code! Modified it to jQueryiedly scroll to the first term or to scroll back to the top if there is nothing found:

    keyup(function() {
            $(instance.textWrapper).html(instance.getOriginalText());
    
            if (this.value.length >= instance.startSearchingLength) {
              var searchText = escape(this.value);
              var regx = new RegExp("(" + searchText + ")", 'gi');
              var selector = 'p:Contains("' + searchText + '")';
              $(instance.textWrapper).each(function() {
                var text = $(this).html();
                text = text.replace(regx, '$1');
                $(this).html(text);
              });
    		  $(function(){
    				$('html, body').animate({scrollTop:$('#scrollToMe').offset().top}, 'slow');
    				return false;
    			});
            }
    		else
    		{
    			$(function(){
    				$('html, body').animate({scrollTop:0}, 'slow');
    				return false;
    			});
    		}
          })
    

    However this script is almost completely unusable because of the html code highlighting also!! has anyone found a solution to that?

    For clarification: in the example try searching for ’str’– this will add the span tag around the character that appear inside the tag in side the HTML

Trackbacks

Check out what others are saying about this post...
  1. [...] “Search on this Page” using jQuery [...]

  2. JQuery – A Fresh Look at What YOU Can Do On SharePoint Without Server Code…

    Client side coding has taken a leap in the right direction, and SharePoint people need to take note….

  3. JQuery – A Fresh Look at What YOU Can Do On SharePoint Without Server Code…

    Client side coding has taken a leap in the right direction, and SharePoint people need to take note….




Notify me of comments to this article:


Speak and you will be heard.

We check comments hourly.
If you want a pic to show with your comment, go get a gravatar!