tags:

views:

97

answers:

2

Here's my code that does work:

function mouseOver()
{
    $(".beaver").fadeIn(100);

}

function mouseOut()
{
    $(".beaver").fadeOut(100);
}

$("#group_beaver").bind('mouseenter', mouseOver).bind('mouseleave', mouseOut);

But why doesn't this work?

function mouseOver(variable)
{
    $(variable).fadeIn(100);

}

function mouseOut(variable)
{
    $(variable).fadeOut(100);
}

$("#group_beaver").bind('mouseenter', mouseOver('.beaver')).bind('mouseleave', mouseOut('.beaver'));
+5  A: 

That's correct; you're calling mouseOver and expecting it to return a function to be bound to the event. To make it actually do that, though, you can use this code:

function mouseOver(variable) {
    return function() {
        $(variable).fadeIn(100);
    };
}
function mouseOut(variable) {
    return function() {
        $(variable).fadeOut(100);
    };
}
icktoofay
+1 great example.
nickf
Awesome. You just saved me a lot of time. Thank you!
dallen
If this answered your question, please mark it as an answer by clicking the little check on the side of the answer.
icktoofay
+1 - That's clever. I figured you would have to call the function from within the handler. Didn't think of returning a function. Even remains useful as a callable function with `mouseOver('.beaver')();`. Learned something new!
patrick dw
+1 nice example
Gert G
+1  A: 

icktoofay's technique is called a closure. There's an excruciatingly comprehensive discussion of closures here. I find them super useful for scheduling events with window.setTimeout(). They basically allow you to load up a function object with preconditions and then evaluate it with no arguments. Pretty nifty.

However for all their novelty closures can usually be avoided. For instance, if .beaver's are children of #group_beaver you would be better off with something like

function mouseOver()
{
    $(this).children().fadeIn(100);
}

In event handlers jQuery makes sure that this always refers to the element that triggered the event, so you've basically got an argument for free. Given the simplicity of your example I'm guessing a closure is not necessary.

You could also do:

$('group_beaver').mouseenter(function() {
    $(variable).fadeIn(100);
});

Which is really just a closure in disguise. Its the same as writing:

function mouseOver(variable) {
    return function() {
        $(variable).fadeIn(100);
    }
};

$('#group_beaver').mouseenter(mouseOver('.beaver'));
jasongetsdown