views:

351

answers:

3

I'm calling the first function below to bind the second function to the onClick event.

The strange thing is that calling the first function results in firing the second function.

The LinkName parameter in the first function is a name of a table td element - probably not relevant.

function EnableExpand(LinkName, i) {
    $(LinkName).addClass("link-text");
    $(LinkName).bind("onclick", ExpandFrame(LinkName, i));
}

function ExpandFrame(lName, i) {
    $("#mapFrame" + i).attr({ height: 500, width: 800 });
}
+3  A: 

You need to pass a function that will be called when the click event happens. The way you had it, you were calling the function immediately, and telling JQuery to call whatever value is returned from that function.

$(LinkName).bind("click", function () { ExpandFrame(LinkName, i); } );
Patrick McElhaney
Correct, but it'd be good to explain why. ;)
Joel Potter
yeah, why?Never mind, it worked, thanks!
GilShalit
+2  A: 

You dont need the bind. .click will do.

$(LinkName).click( function () { ExpandFrame(LinkName, i) } );
redsquare
+1  A: 

The problem is that the second argument to .bind() should be a function, but you are calling a function. JQuery evaluates the function call and tries to bind the result to the click event.

By wrapping the function call in a anonymous function, as suggested, the javascript engine will bind the wrapper function to the event, and not evaluate what's inside it.

$(LinkName).click( function () { ExpandFrame(LinkName, i) } );

It may be helpful to realize that using the following is equivalent to your code above.

$(LinkName).click( function () { ExpandFrame(LinkName, i) }() );
Joel Potter
thank, got love those anonymous functions...
GilShalit
+1 Great explanation!
Patrick McElhaney