Typically, I can pass an event to an anonymous Jquery function like so:
$(".click_me").on("click", function(e) {
e.preventDefault();
});
Now let's say I remove the anonymous function but still want to pass the event to it:
function onClickMe(e){
e.preventDefault();
}
$(".click_me").on("click", onClickMe(e));
Unfortunately, this doesn't work as expected. I get this error:
ReferenceError: e is not defined
So how else can I pass the event to an external function?
Just pass the function reference, jQuery will handle passing the arguments for you (it always passes the event as the first argument to the handler function). So:
function onClickMe(e){
e.preventDefault();
}
$(".click_me").on("click", onClickMe);
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