I’m no JavaScript expert (far from it) and I just have superficial experience with jQuery — nothing too fancy. I’m having the following code:
// show search forms
searchButton = jQuery('#show-search');
searchForm = jQuery('#search-form');
function toggleSearch() {
searchButton.button('toggle');
searchForm.slideToggle(300, function() {
searchForm.find('#value').focus();
});
}
searchButton.on('click', toggleSearch());
When the page loads, the #search-form is in fact activated and it slides down, without the need of calling the function (i.e actually clicking the button).
According to this post I can pass the function like this:
searchButton.on('click', toggleSearch);
And it will do the same as if I was doing this:
searchButton.on('click', function() {
toggleSearch();
});
It works. Both methods do.
- Why does this work and why can’t I just use the first form? (passing
toggleSearch()) - What if there is a variable called toggleFunction with some random value? Wouldn’t it be passed instead of the function?
EDIT: I’m aware of this excellent answer but it doesn’t explain the “reference” part, nor the case of a previously assigned variable. Are annonymous functions neccesary in those cases? Should I just use them every time?
()makes you execute the function, if you usetoggleSearch(), you are passing the return value(※which in your case isundefined) to.on, not the function itself.toggleFunctionis the function name, but also is a variable, it is same asSo if there is another variable called
toggleFunction, thetoggleFunctionwill be changed.