Triggering function with a hot key or function key

Please post an example of how a hot key or function key can be used to trigger any kind of simple js function. I need to understand how that trigger works so I can fill the function with what I need.

My searches have produced plenty of material, but little understanding. For example, is this even possible without a library (straight JS)?

Hi,

You could do it like this (note that code should go just before closing </body> tag):

(function(){
  var el = document.getElementsByTagName('body')[0];

  function keyEvent(event) {
    var key = event.keyCode || event.which;

    if (key === 103) {
       myFunction();
    }
  }

  if (el.addEventListener) {
    el.addEventListener('keypress', keyEvent, false);
  } else if (el.attachEvent)  {
    el.attachEvent('onkeypress', keyEvent);
  }
})();

You might find the following pages useful for further reference:

Thanks fretburner.

I added an alert to myfunction(), but no joy when I pressed 7 Home…

What did I miss?

 <!DOCTYPE html>
<html>
<head>

</head>

<body>


<script>
(function(){
  var el = document.getElementsByTagName('body')[0];

  function keyEvent(event) {
    var key = event.keyCode || event.which;

    if (key === 103) {
		myFunction() {
			alert("Hello World!");
		}
	}
  }

  if (el.addEventListener) {
    el.addEventListener('keypress', keyEvent, false);
  } else if (el.attachEvent)  {
    el.attachEvent('onkeypress', keyEvent);
  }
})();
</script>
</body>
</html>


myFunction was just a placeholder to show where you could insert a call to any previously defined function of your choosing. If you only want to execute a couple lines of code that you won’t need to call from anywhere else in your program, just add them directly inside the IF statement:

if (key === 103) {
    alert("Hello World!");
}

By the way, I forgot to mention in my previous post that 103 is the code for the ‘g’ key - if you want to trigger the function with a different key, you’ll need to change the code. You can find the different codes here: http://www.asquare.net/javascript/tests/KeyCode.html (you need the ‘onKeyPress’ value).

Voila! You’re outstanding fretburner. I hope you hear that a lot. You really helped me understand this process.

Thanks,

niche