Searching Body Text with textRange, part 1: The Basic Script (Page 1 of 5 )
Many websites have search engines that allow visitors to search through the pages of the entire site. That's good, but what if you have single pages that hold a large amount of content by themselves? You might want to provide a way to search through an individual page of your website; your visitors will be grateful for the convenience. This article helps you get started.
Having a search engine built into your site that allows visitors to search through the pages of your website will add value to almost any site, more so as the site gets bigger. But a search engine such as this won't help visitors search through the text on one particular page of your site. Most of the time, this isn't particularly necessary, but for websites made up of pages that contain a lot of information, this kind of search capability is an excellent feature. These days, there is so much information available, from such a wide variety of sources, that if you don't make it as easy as possible for people to find the information they are looking for with the minimum amount of manual scanning of text, they will go elsewhere to find it. A large percentage of surfers are rapidly turning into mouse potatoes (couch potatoes of the 21st century).
Fortunately, IE provides the textRange() object that can be used to turn either a block of text or an entire document (including HTML if you so desire) into a textRange, upon which various methods can be applied. Once such method is the findText() method, that can be used to find a particular letter, word, or sentence. A combination of methods can be used in effect to create an in-document search engine with a scope of the entire body of the document.
There are several ways in which this could be achieved. While the method that this example is based around may not be the easiest, it provides us with an ideal opportunity to look at some other aspects of JavaScript, such as dialog boxes and exception handling. Okay, exception handling may be a slightly grandiose title for what we'll be doing, but it serves as a good introduction to thinking about what a user of your web page could do to it that is outside the normal operational range of parameters, and how you can cope with this behavior if and when it occurs (which it undoubtedly will!).
Next: Main Script Variants >>
More Code Examples Articles
More By Dan Wellman