Search code examples
javascriptjquerykeyboard-eventsjquery-focusout

jQuery: Bind 2 events and execute only one


I have a table where, when I click on a cell, the cell turns editable. If I change the content of the cell, I want to execute an AJAX request to save the data to the database, only if:

  1. Focus out of the cell
  2. Press enter key

The problem is that the event is executed twice if I press "Enter" and once if I focusout of the cell; and I think I know why: enter keypress qualifies as focusout as well. This is the code:

$(document).on('focusout keypress', '.row_data', function(event){..}

I tried to limit that inside the event:

if ( (event.type === "keypress" && event.which === 13) || (event.type === "focusout" && event.which !== 13) ) {...}

but unfortunately, it will not work.

Any idea why this is failing? Any idea how i can make it work?

Thanks in advance!


Solution

  • How about adding a flag to see if this event has already fired before firing again?

    $(document).on('focusout keypress', '.row_data', function(event){
        if ($(this).data('has-event-fired') {
            // Event already fired! Reset our flag and bail!
            $(this).data('has-event-fired', false);
            return;
        }
    
        // First time we're firing here. Set our flag and fire event as normal.
        $(this).data('has-event-fired', true);
    
        // Rest of event handler
    }
    

    That should force your event to only fire once per action, and will reset itself after both events fire. It could get wonky if only one event manages to fire, though, but it's worth a try.