Search code examples
jqueryeventsfunction

Why are non-anonymous functions being executed when using click event handler?


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> 

Solution

  • 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 variable, like this:

    $("button").click(bclick)
    

    The obvious problem with this, though, is the fact that custom arguments aren't passed in. To resolve this, you could pass in an anonymous function that calls your function:

    $("button").click(() => {
      bclick("Button", "Clicked")
    })