Highlight words in text with jQuery
On the right is an example of word-highlighting in a blog post, done with jQuery (my javascript library of choice). I needed to highlight certain words in blocks of formatted text, so I went searching for an existing solution. I found a pretty good starting point, posted by bjarlestam on Stackoverflow. His highlighting function is below. It wraps the word inside a span tag with a class of your choosing.
jQuery.fn.highlight = function (str, className) { var regex = new RegExp(str, "gi"); return this.each(function () { this.innerHTML = this.innerHTML.replace(regex, function(matched) { return "<span class=\"" + className + "\">" + matched + "</span>"; }); }); };
This is nice, because it uses a case-insensitive regular expression to find the word to highlight. However, there is a flaw. If you call this function on an element with non-text child elements, and the tag/attribute names or attribute values match the word to highlight, this function will mess up your HTML. We’d like it to apply only to text nodes.
Read more
Validate that URLs exist using jQuery / PHP
It would be nice to have a pure javascript method of validating that URLs exist. One imagines you could use an AJAX call and verify the HTTP status code (200, 404, etc.) returned. However, browser security does not permit cross-domain AJAX calls. So, this method would only work if you are validating that URLs exist on the same domain.
Perhaps there is a way to use a hidden iframe to test the existence of a URL. I am not aware of a way to get the HTTP status code of a page that loads inside of an iframe, though. I’m not sure it is possible. So you must rely on javascript plus a server-side programming language to perform this validation. I chose jQuery and PHP.
Prefetching Javascript and CSS
Prefetching javascript and CSS files can improve the page load times as users navigate your site. This creates a better user experience and may even improve your search engine rankings.
I’ll describe an easy prefetch technique useful in situations in which you are reasonably sure the user will navigate from Page A to Page B. This situation typically involves the user filling out a form. Chances are high that if a user begins to fill out a form, she will eventually submit it, arriving at Page B. If you prefetch resources that will be needed by Page B, it’ll load faster when the user navigates to it. This is a technique I’m using on our lifespan test.
