Twodordan Twodordan - 1 year ago 164
Javascript Question

JavaScript dollar function, function $() error

I've come across the dollar sign function over the internets and decided to use it for a javascript toggle menu. However, the "$" symbol makes my code fail.

This is what I'm trying to use:

function $() {
var elements = new Array();
for (var i = 0; i < arguments.length; i++) {
var element = arguments[i];
if (typeof element == 'string')
element = document.getElementById(element);
if (arguments.length == 1)
return element;
return elements;

function toggle(obj) {
var el = $(obj); = ( != 'none' ? 'none' : '' );

The $ from "function $(){" seems to break the code. How do you declare this function?
If I replace $ with "anything", it works, but not as a dollar function...

Answer Source

The dollar sign is not a standard Javascript function, but is part of a third party library.

There are two well-known libraries which use the dollar sign in this way.

The older one is called Prototype, but the one which is currently in vogue, and most likely to be the one you've seen in use is JQuery.

Both these libraries would be used by adding a <script> tag to your HTML page, to include the library code, after which you can use their functionality.

Most of the functionality of both these libraries is contained within their respective $() functions. In the case of JQuery, you can also refer to the $() function as jQuery() to prevent namespace clashes, in the event that you wanted to use both of them.

I suggest reading up on JQuery before continuing -- JQuery is very powerful, and adds a lot of functionality, but the coding style for writing JQuery code can be quite different from regular Javascript, and can take a bit of getting used to. And that's quite apart from learning the API and finding out what it can do.

To actually answer your question -- which is how to declare $ as a function name, I suggest having a look at the JQuery source code to see how they do it. However, I managed to produce a working $() function first time I tried, like this:

var $ = function() {alert('dollar works for me');}

But to be honest, I wouldn't do that. If you really want to use the $() function in the way it's being used in other sites, you need to use JQuery. It does a whole lot more than just wrapping document.getElementById().

By the way, JQuery and Prototype are not the only similar libraries out there. If you're interested in this sort of thing, you may also want to look into MooTools, YUI, and a few others.

Hope that helps.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download