Search code examples
javascriptjquerykeyboardkeydown

Keydown only with real characters?


simple question: I have input fields with inside-labels! Just like the search-box on this site in the upper right corner. When I start typing the label inside it is hidden.

For accessability reasons I have real tags absolutely positioned behind the actual input field. Therefore I just add a class fill to the inputfield so the background color is no longer transparent.

inputs.keydown(function (e) {
     $(this).addClass(fill);
});

Everything works fine except for a little flaw. Whenever I focus the input field and hit a key like "Shift" "Ctrl" or "CMD" the label disappears. However this is no input yet!

Any idea how to do so?

inputs.keydown(function (e) {
        switch (e.keyCode) {        
            case 13: // Enter
            case 16: // Shift
            case 17: // Ctrl
            case 18: // Alt
            case 19: // Pause/Break
            case 20: // Caps Lock
            case 27: // Escape
            case 35: // End
            case 36: // Home
            case 37: // Left
            case 38: // Up
            case 39: // Right
            case 40: // Down

            // Mac CMD Key
            case 91: // Safari, Chrome
            case 93: // Safari, Chrome
            case 224: // Firefox
            break;
        }

        $(this).addClass(fill);
    });

These would be all the keycodes where I don't want to blur the label! Just when typing real characters the fill-class should be added. Btw. is there a better syntax to write those switch statements with all the cases?


Solution

  • This would only execute the addClass when no case is hit:

    inputs.keydown(function (e) {
        switch (e.keyCode) {        
            case 13: // Enter
            case 16: // Shift
            case 17: // Ctrl
            case 18: // Alt
            case 19: // Pause/Break
            case 20: // Caps Lock
            case 27: // Escape
            case 35: // End
            case 36: // Home
            case 37: // Left
            case 38: // Up
            case 39: // Right
            case 40: // Down
    
            // Mac CMD Key
            case 91: // Safari, Chrome
            case 93: // Safari, Chrome
            case 224: // Firefox
            break;
            default:
              $(this).addClass(fill);
            break;
        }
    });
    

    But since you are using jquery and want a smaller solution try this:

    inputs.keydown(function (e) {
      if($.inArray(e.keyCode,[13,16,17,18,19,20,27,35,36,37,38,39,40,91,93,224])) return;
      $(this).addClass(fill);
    });