13
$(".song").live('click', function songClick() {
    //do stuff
});

Can you name a function like above and then call it at a later point? I tried, but it didn't work. Do I have to pass an event to it?

3 Answers 3

13

Just name it as a standalone function and call it from live():

function songClick() {
  // do stuff
}

$(".song").live('click', songClick);

Note the lack of parens in the live() method.

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

Comments

11

Note for reference's sake:

The live method was removed in version 9. Anyone coming across this question now should use on() instead. But otherwise, should work the same as above answers.

function songClick() {
//code
}

$(".song").on('Click', songClick);


If you only want the event handler to run once you can also use one() as well.

Comments

1

You can define the function before the jquery code, then just pass the name to jquery; i.e.,

function songClick() {
    //do stuff
}
$(".song").live('click', songClick);

You could then use songClick() elsewhere, too.

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.