Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Passing the Event Object to a Function in Jquery

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?

like image 594
nullnullnull Avatar asked Feb 12 '13 16:02

nullnullnull


1 Answers

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);
like image 163
Anthony Grist Avatar answered Oct 02 '22 15:10

Anthony Grist