1

So normally, I do it like this:

$('#selectRoom a').click( function(e) { 
e.preventDefault(); // To prevent the default behavior (following the link or adding # to URL)
// Do some function specific logic here
});

However, I would like to do it like this, to clean things up (and be able to reuse):

$('#selectRoom a').click( selectRoom );

function selectRoom () {
    e.preventDefault(); // To prevent the default behavior (following the link or adding # to URL)
    // Do some function specific logic here
}

The problem is, i cant pass the "e" event-handler to the function, then the selectRoom() function is called on load. i.e:

$('#selectRoom a').click( selectRoom(e) );

Can I fix this somehow?

3 Answers 3

6

selectRoom() will be given the event:

function selectRoom(e)

That should work.

Sign up to request clarification or add additional context in comments.

Comments

2

Declare it like this:

function selectRoom(e) {
  // now e will work
}

Do not do this:

$('#selectRoom a').click(selectRoom(e)); // WRONG DO NOT DO THIS

because that means, "Call the function selectRoom and then pass its return value to the "click" function in jQuery." You want to pass jQuery the name of the funcion, not the result of executing the function. Thus:

$('#selectRoom a').click(selectRoom);

Comments

0

You can also return false from the function to prevent the event from continue to bubble.

Comments

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.