Content
You are here:
Manipulating the DOM with $(sel) instead of jQuery(sel)
Added by Kiffin Gish almost 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 jquery
to the manifest. Any ideas on the best approach?If I understand the documentation correctly, jQuery with
jQuery.noConflict()
not set will listen tojQuery
as 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.erb
manifest:So I solved the problem like this:
Hi Kiffin,
an alternative would simply be an anonymous function exposing
$
in an anonymous function. Whichever you prefer.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 dowithout 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:
I get the following error:
Whereas, when I wrap it with:
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, thejQuery
stuff has not yet been initialized.Could I be missing soemthing?