10

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> 

3 Answers 3

23

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")
})
Sign up to request clarification or add additional context in comments.

4 Comments

You could if you use $("button").click(function(){bclick("Button", "Clicked");});
This is a trivial example, I know, but this was where I got stuck in something more complicated. Thanks a lot!
thank you! you saved my keyboard from going into pieces I cannot believe there is such a big difference between $("button").click(bclick); and $("button").click(bclick());
thx that helps, you can pass this as well function() { funcName($(this)); }
1

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.

1 Comment

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

If you want to pass arguments when setting up your event handler, another alternative is to return a function.

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

function bclick(foo, bar) { // called once when the event handler is setup
    return function(e) { // called every time the event is triggered
        // you still have the original `foo` and `bar` in scope,
        // and a new `e` (event object) every time the button is clicked
        console.log(foo, bar, e);
    };
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.