jQuery in Action
164
CHAPTER 6
jQuery utility functions
the definition of the
$
variable is the largest point of contention and conflict when
using other libraries on the same page as jQuery. As we know, jQuery uses
$
as an
alias for the
jQuery
name, which is used for every feature that jQuery exhibits. But
other libraries, most notably Prototype, use the
$
name as well.
jQuery provides the
$.noConflict()
utility function to relinquish control of
the
$
name to whatever other library might wish to use it. The syntax of this func-
tion is as follows:
Because
$
is an alias for
jQuery
, all of jQuery's functionality is still available after
the application of
$.noConflict()
, albeit by using the
jQuery
identifier. To com-
pensate for the loss of the brief--yet beloved--
$
, we can define our own shorter,
but non-conflicting, alias for
jQuery
, such as
var $j = jQuery;
Another idiom often employed is to create an environment where the
$
name is
scoped to refer to the
jQuery
object. This technique is commonly used when
extending jQuery, particularly by plugin authors who can't make any assumptions
regarding whether page authors have called
regarding whether page authors have called
$.noConflict()
and who, most cer-
tainly, can't subvert the wishes of the page authors by calling it themselves.
This idiom is as follows:
(function($) { /* function body here */ })(jQuery);
If this notation makes your head spin, don't worry! It's pretty straightforward if
odd-looking to those encountering it for the first time.
odd-looking to those encountering it for the first time.
Let's dissect the first part of this idiom:
(function($) { /* function body here */ })
Function syntax: $.noConflict
$.noConflict()
Restores control of the $ name back to another library, allowing mixed library use on pages
using jQuery.
Once this function is executed, jQuery features will need to be invoked using the jQuery
name rather than the $ name.
using jQuery.
Once this function is executed, jQuery features will need to be invoked using the jQuery
name rather than the $ name.
Parameters
none
Returns
Undefined.
Undefined.