0

I have the following code,

<script src="//ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js" type="text/javascript">
alert($().jquery); // Version 2.1.0
jQuery.noConflict();
alert($().jquery); // Previous version
</script>

Where I would like to use the 2nd version to do some stuff, then return the $ variable back to the first version, so existing jQuery functions still work. But when I run this, $().jquery returns version 1.3.2, which is the old version. Anyone able to help?

Thanks

AkshaiShah
  • 5,739
  • 11
  • 37
  • 45
  • Maybe change the order of your `script` tags? Why are you using multiple versions of jQuery in the same page? – JLRishe May 17 '14 at 13:47
  • @JLRishe I can't do that as the rest of the html is generated automatically through a plugin. As the rest of the website uses version 1.3.2, but the functionality I am adding requires a newer version. – AkshaiShah May 17 '14 at 13:49
  • So what's the problem? Store a reference to the 2.1.0 version using `noConflict()`, and then for the rest of the code, `$` will be treated as version 1.3.2. – JLRishe May 17 '14 at 15:26

1 Answers1

1

As jQuery API says so,

If for some reason two versions of jQuery are loaded (which is not recommended by jQuery API), calling $.noConflict( true ) from the second version will return the globally scoped jQuery variables to those of the first version.

<script src="other_lib.js"></script>
<script src="jquery.js"></script>

<script>
$.noConflict();
// Code that uses other library's $ can follow here.
</script>

This technique is especially effective in conjunction with the .ready() method's ability to alias the jQuery object, as within callback passed to .ready() you can use $ if you wish without fear of conflicts later:

<script src="other_lib.js"></script>
<script src="jquery.js"></script>

<script>
$.noConflict();
jQuery( document ).ready(function( $ ) {
// Code that uses jQuery's $ can follow here.
});
// Code that uses other library's $ can follow here.
</script>

In one project I've used it as

var j = jQuery.noConflict();
// Do something with jQuery
j( "div p" ).hide();

Also like this

jQuery.noConflict();
  (function( $ ) {
    $(function() {
    // More code using $ as alias to jQuery
   });
})(jQuery);

I hope this helps.

Ekin
  • 1,957
  • 2
  • 31
  • 45