Skip to content
Advertisement

How to run a function only once when it’s triggered by both focus and click events

I have an input element with 2 events attached: focus and click. They both fire off the same helper function.

When I tab to the input, the focus event fires and my helper is run once. No problems there.

When the element already has focus, and I click on it again, the click event fires and my helper runs once. No problems there either.

But when the element does not have focus, and I click on it, BOTH events fire, and my helper is run TWICE. How can I keep this helper only running once?

I saw a couple similar questions on here, but didn’t really follow their answers. I also discovered the .live jQuery handler, which seems like it could work if I had it watch a status class. But seems like there should be a simpler way. The .one handler would work, except I need this to work more than once.

Thanks for any help!

Advertisement

Answer

The best answer here would be to come up with a design that isn’t trying to trigger the same action on two different events that can both occur on the same user action, but since you haven’t really explained the overall problem you’re coding, we can’t really help you with that approach.

One approach is to keep a single event from triggering the same thing twice is to “debounce” the function call and only call the function from a given element if it hasn’t been called very recently (e.g. probably from the same user event). You can do this by recording the time of the last firing for this element and only call the function if the time has been longer than some value.

Here’s one way you could do that:

function debounceMyFunction() {
    var now = new Date().getTime();
    var prevTime = $(this).data("prevActionTime");
    $(this).data("prevActionTime", now);
    // only call my function if we haven't just called it (within the last second)
    if (!prevTime || now - prevTime > 1000) {
        callMyFunction();
    }
}

$(elem).focus(debounceMyFunction).click(debounceMyFunction);
User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement