Chapter 4. jQuery Utilities
Introduction
Often, when thinking and talking about jQuery, the main concepts that come to mind are DOM and style manipulation and behavior (events). Yet there are also a number of “core” features and utility functions tucked away for the developer’s benefit. This chapter is focused on exposing, disclosing, and explaining these not-so-common utility methods of jQuery.
4.1. Detecting Features with jQuery.support
Problem
You need to attach a special click handler to all anchor tags that have just a hash for the current
page, and you don’t want to risk it breaking because of browser
support issues.
Solution
(function($) {
$(document).ready(function() {
$('a')
.filter(function() {
var href = $(this).attr('href');
// Normalize the URL
if ( !jQuery.support.hrefNormalized ) {
var loc = window.location;
href = href.replace( loc.protocol + '//' + loc.host + loc.pathname,
'');
}
// This anchor tag is of the form <a href="#hash">
return ( href.substr(0, 1) == '#' );
})
.click(function() {
// Special click handler code
});
});
})(jQuery);Discussion
The jQuery.support object
was added in version 1.3 and contains Boolean flags to
help write code using browser feature detection. In our example,
Internet Explorer (IE) has a different behavior in how it handles the href attribute. IE will return the full URL
instead of the exact href
attribute. Using the hrefNormalized
attribute, we have future-proofed our solution in the event that a later version of IE changes ...