124697
124697

Reputation: 21893

How do I fire only one event at a time

$(".timeSeenInput").on("focusout keypress",function(event){
        alert($(this).attr("id"))
    })

I need to detect when the user tabs away from an input box or when pressing away from it. the code above fires twice for when I press a key. how do I make it either fire for either tab or focusout but not both?

Upvotes: 0

Views: 158

Answers (4)

A. Wolff
A. Wolff

Reputation: 74420

You could debounce it a little:

http://jsfiddle.net/wVbeB/

(function () {
    var timeout;
    $(".timeSeenInput").on("focusout keypress", function (event) {
        if (!timeout) {
            var self = this;
            timeout = setTimeout(function () {
                console.log(self.id);
                timeout = null;
            }, 0);
        }

    })
})();

Upvotes: 1

Jai
Jai

Reputation: 74738

This will only fire when tab key is pressed and focusout is happened:

$(".timeSeenInput").on("focusout keydown", function (e) {
   var kc = e.which || e.keyCode;
   if (kc === 9) {
      alert('focusout with tab only');
   }
});

Upvotes: 0

Matt Harrison
Matt Harrison

Reputation: 13567

This is what the blur event is for.

Fiddle: http://jsfiddle.net/DPh6P/

$(".timeSeenInput").on("blur", function (event) {
    alert($(this).attr("id"))
})

Upvotes: 0

Konstantin Dinev
Konstantin Dinev

Reputation: 34895

Tabbing out is produced by both events. You can flag your tabbing out event and not handle the blur:

var handleBlur = true;
$(".timeSeenInput").on("focusout keypress",function(event) {
    if (event.type === 'keypress' && event.keyCode === TAB) {
        alert($(this).attr("id"));
        handleBlur = false;
        return;
    } else if (event.type === 'blur' && handleBlur) {
        // Handle blur
    }
    handleBlur = true;
});

Upvotes: 0

Related Questions