Sporadically, over the course of each month, we’ll post a “Dissecting jQuery” video quick tip. The idea behind these is that we’ll take a single chunk of the jQuery source at a time, break it down, and determine exactly what’s going on under the hood, so to speak. Then, with that knowledge, we’ll learn how to better utilize the library in our coding. Today, we’ll review filters.
Video Tut
Premium Members: Download this Video ( Must be logged in)
Subscribe to our YouTube page to watch all of the video tutorials!
jQuery’s Source for the :hidden
Filter
jQuery.expr.filters.hidden = function( elem ) { var width = elem.offsetWidth, height = elem.offsetHeight, skip = elem.nodeName.toLowerCase() === "tr"; return width === 0 && height === 0 && !skip ? true : width > 0 && height > 0 && !skip ? false : jQuery.curCSS(elem, "display") === "none"; };
The :visible
Filter
Quite cleverly, the :visible
filter only needs to call the hidden
method, and return the reciprocal.
jQuery.expr.filters.visible = function( elem ) { return !jQuery.expr.filters.hidden( elem ); };
Hint: Search for
filters:
andsetFilters:
within the jQuery source code to view a listing of other helpful filters that are available to you.
Harnessing this Knowledge to Extend jQuery
<script> $('p:first').data('info', 'value'); // populates $'s data object to have something to work with $.extend( jQuery.expr[":"], { block: function(elem) { return $(elem).css("display") === "block"; }, hasData : function(elem) { return !$.isEmptyObject( $(elem).data() ); } } ); $("p:hasData").text("has data"); // grabs paras that have data attached $("p:block").text("are block level"); // grabs only paragraphs that have a display of "block" </script>
Note:
jQuery.expr[':']
is simply an alias forjQuery.expr.filters
.
Stay tuned. In future episodes, we’ll continue to slice out more chunks of the jQuery source, and dissect them!