Question

I have a textfield on which I'm detecting every keypress like this:

document.getElementById("postcardText").addEventListener('keyup', checkInput, false);

in my checkInput-function I'm checking only for the letters I want users to add. It works fine so far, the problem is that if the user presses the shift-button e.g. shift+A to write a capital A there are 2 keyups detected and A is added twice. can anyone suggest a workaround?

EDIT: this seems to do the job:

var shiftKey=false;
$(document).keyup(function (e) {
    if (e.keyCode == 16) {
        //alert("Shift was pressed");
        shiftKey=true;
    } else{
      shiftKey=false;
      checkInput();
    }
});

and then in my if-statement something like this

function checkInput(){
    if (character=="A" ||
        character=="B" &&
    shiftKey==false){
    //adding letter-image here
    }
}

I had to change keydown to keyup, otherwise it doesn't detect the first character immediately, but only when the next key is pressed.

Was it helpful?

Solution

From your comment:

basically this is a "machine" that transforms the input text into a colorful image. so each letter has a image that it is represented by. I want that the user while writing already sees how it looks like. I am on each keyup reading the data of the textfield and then adding the last letter as an image to my big image. but the shift-button disturbs things...

Would it be too much to rebuild the entire design from scratch every time on keyup? Each time a keyup event is received, wipe away the current image, and loop through each character of the textfield to add its image.

$(document).keyup(function (e) {

    // Do whatever you need to do to clear the image… 

    var myText = $("#postcardText").val();
    for (var i = 0; i < myText.length; i++) {

        var thisChar = myText.charAt(i);

        // Add thisChar to the image…
        addLetter(thisChar);
    }
});

This method has the added benefit that you can handle arrow keys and even deletions without having to write in exceptions for each of those cases.

OTHER TIPS

Are you using jQuery? If yes, you can try to intercept shift key using this:

$(document).keydown(function (e) {
    if (e.keyCode == 16) {
        alert("Shift was pressed");
    }
});

So you can return false or call your function only if the keyCode is different than 16, take a look here

Try this,

if (character=="A" || character=="B"){
  if(shiftKey==false){
     //adding letter-image here
  }
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top