Google Apps Script HTML Service - Can't get Keypress to work

786 views Asked by At

Using jQuery this works fine:

$(document).on('click','a.clickmap',function(e){ alert('h'); }

However I want to do something when a key is pressed. I've tried both of these:

$(document).on('keypress','body', function(e){
if(e.which==78) {
alert('n');
  // "n"
}

$(document).on('keypress', function(e){ //ditto };

Neither works!

1

There are 1 answers

0
Alan Wells On

I just tried this code in HTML Service, and it worked:

<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>

<script>
var i=0;
$(document).ready(function(){
  $("input").keypress(function(){
    $("span").text(i+=1);
    alert("hah! it actually ran.  I don't beleive it!");
  });
});
</script>

Enter your name: <input type="text">
<p>Keypresses: <span>0</span></p>

That code works for keypresses in the input box, not anywhere in the body, but I changed:

$("input").keypress(function(){

to:

$("body").keypress(function(){

and put some <body></body> tags in my HTML and it worked. The Google documentation does suggest to not use <body> tags.

Google Documentation Link

I'd copy the basic structure of this code that works, get something to work, and then go from there.