Passing event object to function in JQuery

Typically, I can pass the event to an anonymous Jquery function like:

$(".click_me").on("click", function(e) {
  e.preventDefault();
});

      

Now let's say that I am deleting an anonymous function, but still want to pass an event to it:

function onClickMe(e){
  e.preventDefault();
}

$(".click_me").on("click", onClickMe(e));

      

Unfortunately this does not work as expected. I am getting this error:

ReferenceError: e is not defined

      

So how else can I pass the event to an external function?

+3


source to share


1 answer


Just pass the reference to the function, jQuery will handle passing the arguments to 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);

      

+13


source







All Articles