0

I have code:

$(Page).on('click', '*', function(e)
{
    myFunction();
}

function myFunction(){//do something...}

I would like the code in the function to be done only once, now when I click, for example, 5 times, the code from the function myFunction() will be executed 5 times. I don't want to change on('click', '*', ...

3
  • 2
    Use one() instead of on(). It behaves the same, but it unbinds after the first time it executes. Commented Apr 5, 2018 at 16:49
  • 1
    Possible duplicate of Simplest/Cleanest way to implement singleton in JavaScript? Commented Apr 5, 2018 at 16:50
  • a global var? myfunctionRunned = false; and when is executed inside myFunction() just ask if(myfunctionRunned) Commented Apr 5, 2018 at 16:52

2 Answers 2

1

Use jQuery's one method.

Description: Attach a handler to an event for the elements. The handler is executed at most once per element per event type.

Simply change your .on to .one.

$(Page).one('click', '*', function(e) {
  myFunction();
});

function myFunction() {
  // do something
}

Here's the documentation for one

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

Comments

0

You can use the function $.one

$(Page).one('click', '*', function(e)
     myFunction();
});

Or, better:

$(Page).one('click', '*', myFunction);

Be careful with that event delegation who will bind the event click to the whole set of elements within the DOM tree of Page.

1 Comment

Uh, it doesn't bind to all of them, it just matches against all the children. It's still just bound to whatever Page is.

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.