1

How would I make my side menu open when I use the arrow keys? Right arrow key opens it left arrow key closes it.

Here's the code of how my menu opens and closes:

<script>
function toggle() {
  if( document.getElementById("hidethis").style.display=='none' ){
    document.getElementById("hidethis").style.display = '';
  }else{
    document.getElementById("hidethis").style.display = 'none';
  }
</script> 

I have looked into this topic but not been able to find anything that relates directly to me if you could maybe show me or point me in the right direction that would be great. I'm sure you could do this with some sort of keydown function just not sure how.

apples
  • 137
  • 2
  • 6
  • 16
  • Maybe this can help you http://stackoverflow.com/questions/1402698/binding-arrow-keys-in-js-jquery – Marques Nov 03 '13 at 14:07

3 Answers3

3
document.addEventListener("keydown", function (e) {
    if (e.keyCode === 39)
        document.getElementById("hidethis").style.display = '';
    if (e.keyCode === 37)
        document.getElementById("hidethis").style.display = 'none';
}, false);

should do the trick.

Sgoldy
  • 786
  • 3
  • 14
2

Here is the Javascript code that tells if the right or left arrows have been pressed:

<!DOCTYPE html>
<html>
<head>
    <script>
        var thisKey;

        document.onkeydown = keyHit;
        var ltArrow = 37;
        var rtArrow = 39;
        function keyHit(evt) {
            if(evt) {
                thisKey = evt.which;
            } else {
                thisKey = window.event.keyCode;
            }
            if (thisKey == rtArrow) { //Right arrow key is pressed
                document.getElementById("hidethis").style.display = '';
            } else if (thisKey == ltArrow) { //Left arrow key is pressed
                document.getElementById("hidethis").style.display = 'none';
            }
        }
    </script>
</head>
<body>   
</body>
</html>

I hope this helps!

416E64726577
  • 2,214
  • 2
  • 23
  • 47
0

Try jquery keycode av on jquery webpage In normal javascript its char

Stefan van de Laarschot
  • 2,154
  • 6
  • 30
  • 50