views:

76

answers:

3

I was reading a post by David Walsh on creating a sprite menu with MooTools. I am fairly new to MooTools, and I did not understand the way he opened his script. In particular, what is

(function($){
..
})(document.id)

Is it a type of JS closure?

Here is the full script if you don't want to follow the link:

(function($) {
    window.addEvent('domready',function() {
 $('nav').getElements('li').each(function(li) {
  //settings
  var link = li.getFirst('a');
  //fix background image
  if(!li.hasClass('current')) {
   link.setStyle('background-image','none');
  }
  //utility div
  var div = new Element('div',{
   'class': 'nav-' + li.get('id'),
   opacity: 0
  }).inject(li);
  //background imagery
  li.addEvents({
   mouseenter: function() {
    div.fade('in');
   },
   mouseleave: function() {
    div.fade('out');
   },
   mousedown: function() {
    div.addClass('nav-' + li.get('id') + '-click');
   },
   mouseup: function() {
    div.removeClass('nav-' + li.get('id') + '-click');
   }
  });
 });
});
})(document.id);
+4  A: 

(function($){ .. })(document.id)

If you put a function inside (), JavaScript will automatically execute that function. By adding (document.id) he is also passing a parameter to that function. For instance..

(function(message){ alert(message); })( 'Hello World!' );

Would alert Hello World!

William
Thanks, that is exactly what I was looking for.
Rob Lund
+1  A: 

It assigns document.id (a function created by MooTools) to a local variable (named "$") of the anonymous function's scope.

Eli Grey
A: 

It's an auto-executing closed function using Mootools "dollar safe mode".

Nic Bell