In native js you can attach events, via onClick, onKeyPress, ... etc element attributes.
Do not forget, the event parameter in the event handler function ;)
In different browsers, you can read the code of pressed key via different attribute of the event.
Here is an example:
<script type="text/javascript">
document.getElementsByTagName("body")[0].onkeypress=function(e){
var s = String.fromCharCode(e.which | evt.witch );
switch(s){
case "f":
alert("key is 'f'");
break;
....
}
};
</script>
Or You can use the addEventListener
method, like this:
<script type="text/javascript">
document.getElementsByTagName("body")[0].addEventListener('keypress',function(e){
var s = String.fromCharCode(e.which | evt.witch );
switch(s){
case "f":
alert("key is 'f'");
break;
....
}
});
</script>
You should run these scripts after document loaded. You can subscribe the domready
event like this:
<script type="text/javascript">
document.addEventListener( "DOMContentLoaded", function(){
//your code here (one of the above)
}, false );
</script>
This last section is discussed here: javascript domready?. Unfortunetly you can subscribe domready event different ways depends on the client browser.
A sugggestion (offtopic):
There is a bunch of problems when you use native javascript, because of the browser's uncombatibilities, what is already resolved in jQuery
. If you want to use jQuery
, but you can not access the html code, and you want to load jQuery
You can include jQuery
to your site from the CDN
url, with javascript too, like this:
<script>
(function() {
var jQ = document.createElement('script'); jQ.type = 'text/javascript';
jQ.async = true;
jQ.src = '//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js';
var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(jQ, s);
})();
</script>
As the google makes in analitycs code ;)