Search code examples
javascriptjqueryjquery-events

Call different events based on user input style in JavaScript


I have a div which contains an input element to enter some values. These values are added just above the div as a list element upon pressing enter or onFocusOut event. To this point it is fine. But if user types some value and does not press enter and directly clicks on save button, the onFocusOut function for that div should not be called. Instead it should take that typed value and call some save function. Do you have any suggestion on how to detect it?

My code snippet is here:

JS:

 divInput.onkeypress = function (event){
                return someTestFunc();
    }
    
    
    divInput.tabIndex="-1";

    $(divInput).focusout(function (e) {
        if ($(this).find(e.relatedTarget).length == 0) {
            addToList();
        }
    });

Solution

  • It is not a very delicate solution, but you could use a setTimeout before adding the item to the list and clear the setTimeout on save.button click. Try this:

    var $saveButton = $('#exampleButton')[0],
        $divInput = $('#exampleInput')[0],
        timedEvent = -1;
    
    $($saveButton).on('click', function(event){
        if(timedEvent) {
            clearTimeout(timedEvent)
        }
        alert('not add to list & save');
    })
    
    
    $divInput.tabIndex="-1";
    
    $($divInput).on('focusout', function(e) {
        timedEvent = window.setTimeout(function() {
            if ($(this).find(e.relatedTarget).length == 0) {
                alert('add to list');
            }
        }, 200);
    });
    

    Check this working fiddle