Confused - jQuery Function?

Hi all, I’m a little confused on how and why I need to use the function in jQuery, such as the following example:


$('#showButton').click(function() {
     $('#disclaimer').show();
});

Any help would be appreciated, just need to understand why I need to use if and why I couldn’t just do without it!

Simple native javascript will look something like this…

document.getElementById('showButton').onclick = function() {
    document.getElementById('disclaimer').style.display = 'block';
}

Hi there, thank you for your message. Still a little confussed why I need to use the word function, what’s the point? Can’t seem to find much information on this one. Cheers dude :slight_smile:

Sorry got confused by what you meant.

The basic logic behind using an “Anonymous” function is so you can use structured code inside a method/object, without using a function the code would not work and you would end up getting errors resulting in a useless script.

A good example of this is using jQuery’s [B]fadeIn/B and [B]fadeOut/B methods, both essentially do the same thing just in reverse but the options you can pass to it are not limited. For instance the below is a small snippet of 2 versions of the exact same code just using an “Anonymous” function to execute an alert box.

$('a').click(function(e) {
    e.preventDefault();
    
    $(this).fadeOut(function() {
        alert('done');
    });
});

The above uses an “Anonymous” function to create an alert box which wouldn’t have been possible unless we declared the [B]alert/B function after the [B]fadeOut/B method.

$('a').click(function(e) {
    e.preventDefault();
    
    $(this).fadeOut(2000, function() {
        alert('done');
    });
});

Basically the above is the same as the first example but this time i passed 2 arguments to the [B]fadeOut/B method but because jQuery knows and understands this we can still execute the code we want within the “Anonymous” function but as an argument collection rather then a single argument.

Another key use for “Anonymous” functions is been able to pass parameters back to the function like in the example above where e is a parameter which is an object of window.event. Using the “Anonymous” function allows us to take advantage of that parameter and use it to prevent the default action of the anchor link and continue on with the code we set out to use.

Its not as detailed as some people but its the basic understanding of it, hope it helps.