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>
Because you need a function that gets called only in the instant that the button is clicked. If you pass alert('click') then the parser will find a function call and execute it instantly when it is going over that file.
More generally, the point of using anonymous functions is that they do not require a name, because they are "event handlers" bound to a specific event on a specific object. In this case, the object is the entire Document Object Model, and the anonymous function executes when the entire DOM has loaded.
Anonymous functions are often arguments being passed to higher-order functions or used for constructing the result of a higher-order function that needs to return a function. If the function is only used once, or a limited number of times, an anonymous function may be syntactically lighter than using a named function.
The onclick event generally occurs when the user clicks on an element. It allows the programmer to execute a JavaScript's function when an element gets clicked. This event can be used for validating a form, warning messages and many more. Using JavaScript, this event can be dynamically added to any element.
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 you can't pass in custom arguments.
You could also pass in an anonymous function that calls your function:
$("button").click(function() { bclick("Button", "Clicked"); });
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With