Event handling / onkeypress

Hello,

document.onkeypress=function(event){

if(event.ctrlKey){
  if(event.altKey){
    alert('Hello Wolrd');
  }
}

}

Firefox displays alert box once (which is what I expected). When testing in Opera, alert box is displayed twice. When testing in Chrome, alert box is not even displayed once.

I have read this article but I must admit I can’t really make sense of it.

So, I’m here to seek help and good advice about how to handle events properly.

:slight_smile:

Response to the different keyboard events varies between browsers. After some experimentation I determined that to monitor for Ctrl + Alt + another key, the following seems to work:

<script type="text/javascript">

document.onkeyup = function( e )
{
  var evt = e || window.event;

  if( evt.ctrlKey && evt.altKey )
  {
    alert( 'Ctrl + Alt pressed with scancode ' + evt.keyCode );
  }

}

</script>

Probably best to avoid using these combinations as they could conflict with current or future native functionality.

The event compatibility table shows for the keypress event that firefox and opera incorrectly fire that event when they shouldn’t.

It would be the onkeydown event that you want to use, if you want both ctrl and alt to trigger your alert.
Also, in Internet Explorer it’s not the function event where it gets the information from, but from window.event instead, so it can be useful to make it clear that that’s what is happening.


document.onkeydown = function (evt) {
    evt = evt || window.event;
    if (evt.ctrlKey && evt.altKey) {
        alert('Hello World');
    }
};

Thanks :slight_smile:

:tup: