Skip to Main Content
jQuery Cookbook
book

jQuery Cookbook

by Cody Lindley
November 2009
Intermediate to advanced content levelIntermediate to advanced
480 pages
11h 50m
English
O'Reilly Media, Inc.
Content preview from jQuery Cookbook

Chapter 4. jQuery Utilities

Jonathan Sharp

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 ...

Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

jQuery UI in Action

jQuery UI in Action

TJ VanToll
Head First jQuery

Head First jQuery

Ryan Benedetti, Ronan Cranley

Publisher Resources

ISBN: 9780596806941Supplemental ContentErrata Page