0

So I want to call a function when the space bar is pressed on the page. The only problem is thought that the function can NOT be called if it's focused in an input bar. Any ideas on how to do that?

This code works, but still fires the function when focused in an input bar

$(document).keydown(function(e){
    if (e.keyCode==32) {
     stopplay();
    }
});
user3757990
  • 27
  • 1
  • 4

4 Answers4

1

update to this:

if (e.keyCode==32 && !$(e.target).is(':input')) {
 stopplay();
}

:input is handy if you have other input elems like select, textarea etc it selects all the input elements.

Jai
  • 74,255
  • 12
  • 74
  • 103
1

Demo

Use event.stopPropagation() method, to prevent keydown bubbling.

$(':input').keydown(function(e){
    e.stopPropagation();
});

Update:

If you have to apply the above to other input elements, use $(':input') selector.

Community
  • 1
  • 1
Shaunak D
  • 20,588
  • 10
  • 46
  • 79
  • 1
    I thought you didn't read the question entirely. i took a look at the fiddle and removed the downvote. – r3wt Jul 01 '14 at 10:55
0

Well you can look to see where the event originated:

$(document).keydown(function(e){
    if(!$(e.target).is("input")) {
        // it's NOT from an input!
    }
});
paulslater19
  • 5,869
  • 1
  • 28
  • 25
0

Use this code

$(document).keydown(function(e){
    if (e.keyCode==32 && !$(e.target).is("input")) {
     stopplay();
    }
});
demonofthemist
  • 4,081
  • 4
  • 26
  • 45