Short answer
Instead of using the global property event
, declaring it as an argument to your function.
Instead of keyCode
use key
for the character keys, shiftKey
, ctrlKey
, altKey
and metaKey
for the uppercase keys, control, alt and Windows / Commmand ( Mac) respectively.
Explanation
In Firefox for Windows the question code does not work, it returns
"ReferenceError: event is not defined"
This happens because in Internet Explorer and Chrome event
is a global property but it does not happen in Firefox.
On the other hand, according to link both keyCode
as which
are obsolete properties and instead the use of key
is recommended. The properties shiftKey
, ctrlKey
, altKey
and metaKey
will return true
if the corresponding key has been pressed.
Apart from being obsolete, not all browsers are compatible with these properties.
An additional alternative is the use of a library such as jQuery which aims to take charge of managing the variants of the different browsers.
Example using "pure" JavaScript
In the following example, the record of the keys pressed is added to the element <input>
and the result is printed to an element <div>
.
var entrada = document.getElementById('entrada');
entrada.addEventListener('keypress',anexar);
var borrar = document.getElementById('borrar');
borrar.addEventListener('click',limpiar);
var salida = document.getElementById('salida');
function anexar(e){
salida.innerHTML += e.key + '<br />';
}
function limpiar(e){
entrada.value = '';
salida.innerHTML = '';
}
<input id="entrada"> <input type="button" id="borrar" value="Borrar">
<div id="salida"></div>
Putting "pure" is because the KeyboardEvent object is not an object of the JavaScript language specification but is part of the Web APIs.
Example using jQuery
One of the purposes of jQuery is to support multiple browsers in a standardized way. Below is an example in which the recommendations mentioned in the short answer section apply, the declaration of the variable to which the event object will be assigned and the use of the key
property.
$('#entrada').bind('keypress', function(e) {
$('#salida').append(e.key + '<br />');
});
$('#borrar').bind('click',function(){
$('#entrada').val('');
$('#salida').text('');
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<input id="entrada"> <input type="button" id="borrar" value="Borrar">
<div id="salida"></div>