What is the (function($)) for in MooTools Javascript
-
05-07-2019 - |
Question
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);
Solution
(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!
OTHER TIPS
It assigns document.id
(a function created by MooTools) to a local variable (named "$") of the anonymous function's scope.
It's an auto-executing closed function using Mootools "dollar safe mode".
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow