Added by Kiffin Gish over 8 years ago
I would like to use jquery in a plugin that I am writing.
As things are currently setup, I need to use the more cumbersome jQuery(sel) and would rather use $(sel) instead.
What is the standard way to use third party JavaScript libraries, and how can I specifically integrate jQuery into my plugin?
Replies (8)
This has historic reasons but the reason should no longer exist.
The js functionality used to be implemented in prototype and thus
$was already taken. But as prototype has been removed, it should now be possible to change that. PRs welcome.There seem to be alot more dependencies on
jQuery(sel)which depend on its presence. This makes things much more complicated than just addinggem 'rails-jquery'to the Gemfile and//= require jqueryto the manifest. Any ideas on the best approach?If I understand the documentation correctly, jQuery with
jQuery.noConflict()not set will listen tojQueryas well as$. So removing the code in OpenProject should be all right.As it turns out, removing the code in OpenProject is not necessary, because it has already been commented out in
application.js.erbmanifest:So I solved the problem like this:
var $ = jQuery.noConflict(); $(document).ready(function() { $("#logo").hover( function enter() { $(this).attr("style", "border: 3px solid red;"); }, function leave() { $(this).removeAttr("style"); } ); });Hi Kiffin,
an alternative would simply be an anonymous function exposing
$in an anonymous function. Whichever you prefer.(function($) { $('.foobar')... })(jQuery);Best,
Oliver
That’s true, in fact more elegant. I was running with the
jQuery.noConflict()suggestion and overlooked the more obvious.But if it is already commented out you will already be able to call jQuery via the
$directly, meaning you can already do$('.foobar')...without the wrapping if you choose to.
I tried it out in the console and it is working as expected.
Note to self - we should still remove the js file to avoid further confusion.
Well, that was the original problem I had which was the reason for this thread. Namely, if I try:
$(document).ready(function() { ... });I get the following error:
Whereas, when I wrap it with:
(function($) { ... })(jQuery);Everything works just fine.
Yes indeed, typing
$(...)works just fine in the debug console, but something is telling me that when my plugin is loaded, thejQuerystuff has not yet been initialized.Could I be missing soemthing?