Question

Is there any JavaScript function that can unify $ function from both Prototype and jQuery?

Yes, this is the real use case I am facing now. I find $ function in Prototype and $ in jQuery is conflicting each other. I know that we could us jQuery.noConflict() to ressign $ back to Prototype, however by doing so, I will have to rewrite jquery-specific javacript code that use that $ function, or have jquery specific in a code block (eg. anonymous function).

Is there any easier way, without having to rewrite existing code in both library and have them in one page?

The code that could answer this question may look like this, and your feedback is greatly appreciated:

<script type="text/javascript" src="/path/to/prototype.js"></script>
<script type="text/javascript" src="/path/to/jquery.js"></script>
<script type="text/javascript">
/* <![CDATA[ */
var $j = jQuery.noConflict();
var $p = $; // reference to prototype's $
var $ = function(E, F){
  var isJQuery = true;

  //TODO: logic to determine which $ to use here YOUR SUGGESTION HERE ;-)

  var result = null;
  if(isJQuery){
    result = $j(E, F);
  } else { // prototype
    //TODO: code to delegate prototype $
  }

  return result;
}
/* ]]>*/
</script>

// ... any existing javacode jQuery and Prototype using $ function. 

Thanks.

update: Rewrite question to be more clear.

Was it helpful?

Solution

Well, first of all, I can rarely find usefull cases where both of the libraries have to be included in the same page. So you might consider to remove one.
I guess that this is due to a plug-in use, but have a look at the opponent plug-in list, I'm quite sure that there is an alternative.

Second, for your jQuery specific code, it's quite easy to rewrite it, using the anonymous function trick:

(function($){
  ... your code here ...
})(jQuery);

This will work in most of the cases where you don't put global variables or methods rather than binding them to events.

OTHER TIPS

I've always got into the habit of putting all my jQuery code into a function, similar to gizmo's example:

jQuery(function($) {
    // jQuery code here, using $
});

this is the same as the document.ready event handler.

jQuery's been great about making sure they play well with Prototype. Check this page for details, Avoiding Conflicts with Other Libraries.

I've seen both libraries used in the same pages before and it is generally because of third-party apps that are in your pages that use one library while your pages use the other. However, if you're doing all the development yourself, I suggest sticking with one or the other.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top