By default, the jQuery selectors are pretty advanced. You can select items by classes, ids, attributes, the first, the last, etc… But why stop there? By simply extending jQuery, we can add our own custom selectors to further enhance how we use jQuery. In this example, I will create an extended function called widthOver300 leveraging jQuery’s $.extend
Reviewing jQuery’s toggle
Let’s begin by looking at a basic, pre-existing, jQuery selector:
[code]
$(“.myClass:first”).toggle();
[/code]
In the above code example, I am toggling the first element that jQuery finds with the class name of myClass. This will either show or hide the element based on it’s current display CSS property.
Creating a jQuery selector
Now, what if I want to find an element with the name of myClass that has a width of over 300 pixels? It would be nice to do something like this:
[code]
$(“.myClass:widthOver300”).toggle();
[/code]
This can be accomplished with a nice little jQuery extension as follows:
[code]
$.extend($.expr[“:”], {
widthOver300: function (e)
{
return $(e).width() > 300;
}
});
[/code]
With the above code added, if I re-run the previous example, all elements with the class name of myClass that have a width of more than 300 pixels will be toggled on or off.
By extending jQuery, you can add custom selectors to help make your code more readable and reusable. Simply be sure to check jQuery first so that selector doesn’t already exist as you wouldn’t want to reinvent the wheel!