Possible Duplicate:
$(document).ready shorthand
Can someone help me to understand the JS code below, please:
$(function(){ <-- Is this a JS constructor? Why we need this?
var someVariable = $(".classa").on('click', function() { <-- At what point in time does someVariable get populated?
var $this = $(this);
id = $this.attr('id');
someVariable.removeClass('selected');
});
var someVariable2 = $(".classb").on('click', function() {
var $this = $(this);
id = $this.attr('id');
someVariable2.removeClass('selected');
});
});
$is the name of a function. You’re passing an anonymous function inside of it as its first argument. If we were to reduce it in complexity, it would look like this:If we were to call this now, it would look like the following:
In this code,
"foo"is our first argument. Now suppose we replaced our"foo"with another function:If we passed that into our
$function it would look like this:But we really don’t need to use a named function, we could use an anonymous function:
Starting to see the similarities? At some point in the life of
$, it will decide it’s going to execute the function we’re passing in. Until it executes it, our function does nothing.Now we’re talking about jQuery here, and jQuery will execute that function whenever the DOM is ready. So we’re passing code in that ought to be executed whenever the DOM is ready.