Avi
Avi

Reputation: 23

How to change the name of the '$' function on Prototype JS library?

I am using both jQuery and Prototype libraries in my application (forced to that because of 3rd party plugins).

Both libraries use the '$' as their core function. I know how to change the $ on jQuery to something else to avoid a conflict. However I prefer to change the Prototype $ function, as most of my code uses jQuery.

Is there a way to do this?

Upvotes: 2

Views: 239

Answers (2)

pete
pete

Reputation: 25081

Has any one tried something like this after both libraries have loaded?

<script>
// using Prototype.js
Event.observe(window, 'load', function () {
    window._ = window.$;    // assign $ to _
    window.$ = jQuery;      // re-assign $ to jQuery
});
// or using jQuery
/*
jQuery(document).ready(function () {
    window._ = window.$;    // assign $ to _
    window.$ = jQuery;      // re-assign $ to jQuery
});
*/
</script>

This should put Prototype.js on _ and jQuery on $.

Failing that, this IIFE pattern should allow you to use $ for jQuery (and for Prototype):

<script>
// do Prototype.js stuff using $
(function ($) {
    $('#myElem').addClassName('hidden').insert('Prototype added class "hidden" so now you cannot see me!);
}(window.$));

// do jQuery things using $
(function ($) {
    $('#myElem').removeClass('hidden').append($('<p />').text('jQuery removed class "hidden" so now you can see me!));
}(jQuery.noConflict()));
</script>

Upvotes: 4

MarZab
MarZab

Reputation: 2623

You have to use non-conflict in jQuery.

Then change the $ to something else. Then you can change $ to jQuery.

$p = $;
$ = jQuery;

Upvotes: 0

Related Questions