8

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?

4
  • 1
    That's an anonymous function, not an "internal" one. Commented Feb 12, 2013 at 16:26
  • @MattBall Thanks for the tip. I've corrected my question. On a similar note, is there a proper term for what I call "external functions"? Commented Feb 12, 2013 at 16:29
  • @timothythehuman Probably just called a function, though an example would help. Commented Feb 12, 2013 at 16:38
  • 1
    The terms are "anonymous" and "named." Way more than you ever wanted to know: kangax.github.com/nfe Commented Feb 12, 2013 at 16:46

1 Answer 1

20

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

4 Comments

Brilliant! I had no idea Jquery was so elegant.
Confused here - preventDefault() is a jQuery function (not internal jscript one). How come then we call it without the $ I would have expected $(e).preventDefault()
@DavidThorisson Because the paramater e in the function is passed a jQuery Event object when the event fires, which has the preventDefault() function.
That works but I'm still looking for a way so that I can pass event and my own parameter in the same function, something like $(".click_me").on("click", onClickMe(event, parameter1));

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.