0

I was writing an javascript application. I used something like

document.keypress = function(e) {
    switch(e.which){ 
    case 97: 
    alert('foobar');
    break;
    .......

And it works fine! Now, somewhere in the html page i have a textarea, Now, whenever i type a (i.e, ASCII 97) then it alert's (obviously).

The question is how do i prevent this? with my keypress event working for everything except inside textareas, and text fields?

cipher
  • 2,414
  • 4
  • 30
  • 54

6 Answers6

4

You can use the target attribute to identify the element that triggered the event. Then, use tagName to figure out the element type.

You can use other properties like type to figure out if it is a text field.

document.keypress = function(e) {
var target = e.target;
var elementType = target.tagName.toLowerCase();
if (elementType != "textarea" && !(elementType =="input" && target.type =="text")) {
    switch(e.which){ 
    case 97: 
    alert('foobar');
    break;
    .......
Lai Xin Chu
  • 2,462
  • 15
  • 29
2

You can specify element/elements to which you'll add event listeners, for example:

document.getElementById('text-field').keypress = function (e) {
    var code = e.keyCode || e.which;
    switch (code) {
        case 97:
            alert('foobar');
            break;
        ....
    } 
}
Emil A.
  • 3,387
  • 4
  • 29
  • 46
1

I think what you are looking for is jQuery's stopPropagation method.

From the docs -

Prevents the event from bubbling up the DOM tree, preventing any parent handlers from being notified of the event.

$(':input').on('keypress', function(e) {
      e.stopPropagation();
});

Working fiddle

When you click inside the textbox, the alert will not be shown. When you click anywhere else in the document, the alert will be displayed.

Raoul George
  • 2,807
  • 1
  • 21
  • 25
1

I can see two possible approaches:

  1. Add onfocus/onblur handlers to your text inputs, to clear/set document.keypress.

  2. Within the handler, get the currently focused element

How do I find out which DOM element has the focus?

And then use the .tagName and .type properties to determine whether it's a text input.

Community
  • 1
  • 1
Stewart
  • 3,935
  • 4
  • 27
  • 36
0

You can use jQuery's keyPress method.

http://api.jquery.com/keypress/

here's how to use it :

$("#target").keypress(function(e) {
  e.preventDefault();
});
Community
  • 1
  • 1
Kyle Emmanuel
  • 2,193
  • 1
  • 15
  • 22
0

try following:

$(document).on("keypress",function(e){
    switch(e.which){ 
      case 97: 
       alert('foobar');
       break;
    }
});

$('textarea,input[type="text"]').on("keypress",function(e){
   e.stopPropagation();
});

here is the fiddle: http://jsfiddle.net/m7ghb/

I hope it helps.

maverickosama92
  • 2,685
  • 2
  • 21
  • 35