Default jquery uses $ as a shortcut for jquery. Thus if
you are using another javascript library that uses $ variable, you can run
into conflicts with jquery. In that
condition you avoid jquery conflicts , put jquery. noConflict () after it is loaded on to the page and before attempt
to use jquery on the page.
JqueryNo-Conflict Mode
When you put jQuery into no-conflict mode, you have the
option of assigning a new variable name to replace the
$
alias. for example
<script>
var $j = jQuery.noConflict();
$j(document).ready(function() {
$j( "div" ).hide();
});
</script>
In this example I
am using
$
. You'll still be able to
use the full function name jQuery
as well as the
new alias $j
in the rest of your
application. The new alias can be named anything you'd like: jq
, $J
, awesomeQuery
, etc.
If you want to use $
and don't care about using the other library's $ method, then another
approach you might try: simply add the $ as an argument passed to your jQuery( document ).ready() function. This is most frequently used in the case where
you still want the benefits of really concise jQuery code, but don't want to
cause conflicts with other libraries.
<script>
jQuery.noConflict();
jQuery( document ).ready(function( $ ) {
$( "div" ).hide();
});
window.onload = function(){
var mainDiv = $( "main" );
}
</script>
Including jQuery Before Other Libraries
If
you include jQuery before other libraries, you may use
jQuery
when you do some work with jQuery, but the $
will have the meaning defined in the other
library. There is no need to relinquish the $
alias by calling jQuery.noConflict()
.<script src="<!—your jquery libraries -->"></script>
<script src="—your javascript libraries --"></script>
<script>
jQuery( document ).ready(
function() {
jQuery(
"div").hide();
});
// Use the $ variable as defined in javascript libraries
window.onload =
function() {
var
mainDiv = $(
"main");
};
</script>
Summary Reference of the jQuery Function
Create jquery alias with noConfilict()
<script>
var
$jq = jQuery.noConflict();
</script>
Immediately Invoked jquery Function Expression
<script>
jQuery.noConflict();
(
function( $ ) {
// Your jQuery code here, using the $
})( jQuery );
</script>
Use the Argument jQuery(document).ready()
Function
<script>
jQuery(document).ready(function( $ ) {
// Your jQuery code here, using $ to
refer to jQuery.
$('.mydiv').show();
$('.mydiv').show();
});
</script>
No comments:
Post a Comment