views:

626

answers:

2

I've been exploring the use of custom functions for event handlers. In this stripped down example, I'm trying to get an alert to pop up when the user clicks a button.

But the alert box pops up immediately as the page loads! What am I doing wrong? ( the commented portion does the exact same thing).

If I define the bclick() function like

function bclick(foo, bar){ ... }

The result is also the same.

JS in the header:

<script type="text/javascript">

var bclick = function(foo, bar){alert( foo + "  " + bar + "\n");}

//$(document).ready(function(){
//    $("button").click(bclick("Button","Clicked"));
//    });

$("button").click(bclick("Button","Clicked"));

</script>

Relevant HTML in the body:

<button>Click Me!</button>
+9  A: 

You're evaluating your function before you even pass it.

$("button").click(bclick("Button","Clicked"));

Here, bclick is called with those arguments, and the result is being passed to the click method. You want to pass it like a normal varialbe, like this:

$("button").click(bclick);

The obvious problem with this, though, is the fact that you can't pass in custom arguments.

EDIT: You could pass in an anonymous function that calls your function (thanks gnarf):

$("button").click(function() { bclick("Button", "Clicked"); });
musicfreak
You could if you use $("button").click(function(){bclick("Button", "Clicked");});
gnarf
Oh yeah, duh. Thanks, I fixed it. :)
musicfreak
This is a trivial example, I know, but this was where I got stuck in something more complicated. Thanks a lot!
No problem! :)
musicfreak
+1  A: 

As musicfreak said. However if you want to be really tricky and use the code you have, then youd just need to add return this at the end of your bclick function.

Darko Z
Thanks, I'll mess around with both, I'm sure!