0

I want on a key press an alert box will get displayed. It is done. But the problem is I have a textbox inside the page and when I am trying typing inside the textbox then also the alert box is coming.

$(document).ready(function() {
    $(document).keydown(function(e) {
        if (e.key == "F8") {
            alert('Right key pressed');
        } else {
            alert("Error key pressed")
        }
        e.preventDefault();
    })
});

HTML:

<input type="text" />
Tushar
  • 85,780
  • 21
  • 159
  • 179
Code
  • 37
  • 1
  • 1
  • 9
  • 1
    Possible dublicate: http://stackoverflow.com/questions/2639956/jquery-how-to-select-all-elements-except-input-and-textarea-to-disable-keydow – Niddro Jul 02 '15 at 11:11
  • 4
    That looks like incredibly annoying functionality. – Liam Jul 02 '15 at 11:12

2 Answers2

2

Textbox is element of your document so it is good behavior that it raise document's events.

You should add handler to textbox to stop propagate event to document layer

$('input').keydown(function (e) {
   e.stopPropagation();
}
suvroc
  • 3,058
  • 1
  • 15
  • 29
  • Yeah, remember though that e.stopPropagation() is IE9 and above. If you plan to support IE8 maybe do `e.stopPropagation = e.stopPropagation || function(){e.cancelBubble = true}` – George Nemes Jul 02 '15 at 11:18
  • @GeorgeNemes - jQuery handles all of that for you. – nnnnnn Jul 02 '15 at 11:35
  • Yeah you're right, jQuery handles that and he's using it. Force of habit. I'll leave the comment for vanilla javascript reference, maybe it will help somebody. Thanks – George Nemes Jul 02 '15 at 11:41
  • @suvroc. If I want the same output using "alt+f" instead of "F8" tyhn what should I do? I tried with the following but failed. ``if (e.key = "F" && e.altKey) {`` – Code Jul 02 '15 at 12:37
0

Try doing it using event listeners:

$(document).ready(function() {
var keyListner = function (e) {
    e.preventDefault();
    if (e.key == 'F8') {
        console.log('Right key pressed');
    } else {
        console.log('Error key pressed')
    };
}

//  Set the event listener
$(document).on('keyup', 'body', keyListner);

// Disable it on focus
$('input, textarea').focus(function() {
    $(document).off('keyup', 'body', keyListner);
});

// Enable it on blur
$('input, textarea').blur(function() {
    $(document).on('keyup', 'body', keyListner);
});
});
FaCE
  • 188
  • 9