Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I capture altKey + i, u, e, n with jQuery?

I'm trying to set up a keyboard for a foreign language. I'm using jQuery to convert keys pressed into foreign characters. I am using:

  • A - Z
  • ALT + A - Z
  • SHIFT + A - Z
  • ALT + SHIFT + A - Z

    My code works for all of these except these 4:

    • ALT + I
    • ALT + U
    • ALT + E
    • ALT + N

It works fine in Firefox, but in Chrome and Safari (I'm using a mac) I get these accent marks - ˆ, ¨, ´, ˜ - instead of the foreign character that is supposed to go into the textarea.

Here is some of the code:

function type(e, char, textArea) {
    e.preventDefault();
    var start = textArea[0].selectionStart;
    var end = textArea[0].selectionEnd;
    var len = textArea.val().length;
    var newPos = start + char.length;
    textArea.val(textArea.val().substring(0, start) + char + textArea.val().substring(end, len));
    textArea[0].setSelectionRange(newPos, newPos);
}
$('textarea').keydown(function(e) {
        var textArea = $(this);
        if (e.which == 65 && e.altKey) {type(e, 'अ', textArea);return false;}
        if (e.which == 68 && e.altKey) {type(e, 'ड', textArea);return false;}
        if (e.which == 73 && e.altKey) {type(e, 'इ', textArea);return false;}
        if (e.which == 74 && e.altKey) {type(e, 'ज्ञ', textArea);return false;}
});

This works when e.which is 65, 68, and 74, but not 73.
How can I get this to work right?

like image 400
twharmon Avatar asked Apr 19 '16 12:04

twharmon


1 Answers

You know it's funny, I'm also constantly asking myself why something doesn't work in chrome even though it works just fine everywhere else. In this case, I'm assuming it has to do with the fact that both e.which and e.keyCode have been depreciated for e.key and e.code.

That being noted, I still use e.keyCode in production, so I know it still works with the latest version of chrome. Maybe do some console.log(e) and see what values are actually being returned?

I don't have chrome on my personal computer, so I can't test this, but I simplified your code and made a fiddle that works on my machine. Hopefully it helps point you in the right direction.

function InsertSymbol(symbol, $selector) {
  let cursor = $selector[0].selectionStart,
      text = $selector.val();
      
  $selector.val(text.substr(0, cursor) + symbol + text.substr(cursor)).focus()[0].setSelectionRange(++cursor, cursor);
}

$('textarea').on('keydown', function(e) {
  if (e.altKey) {
    e.preventDefault();
    
    switch (e.keyCode) {
      case 69: InsertSymbol('इ', $(this)); break;
      case 73: InsertSymbol('अ', $(this)); break;
      case 78: InsertSymbol('ज्ञ', $(this)); break;
      case 85: InsertSymbol('ड', $(this)); break;
    }
  }
});

https://jsfiddle.net/rvgj35kt/2/

like image 118
PoorlyWrittenCode Avatar answered Nov 12 '22 13:11

PoorlyWrittenCode