0

Lets call the 2 divs in question div1 and div2.

What I'm trying to do is use the enter key to show div1 and hide div2 (if div2 is currently visible) and vice-versa. Right now I have the code so that pressing enter will show div1 and hide div2, but to go back to having div2 shown and div1 hidden you have to use the shift key. The way it is now works, but I would like it so I only have to press enter each time I want the divs to alternate.

Here is the javascript code

<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.6.4/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
    var keys = [];
    var code = [13];
    var keys1=[];
    var code1 = [16];
    $(document).keydown(function(keyEvent) {
      keys.push(keyEvent.keyCode);
      keys1.push(keyEvent.keyCode);
      if ( keys.length > code.length ) {
        keys.shift();
      }
      if ( keys1.length > code1.length ) {
        keys1.shift();
      }
      if ( keys.toString() == code.toString() ) {
        showAns();
      }
      if ( keys1.toString() == code1.toString() ) {
        hideAns();
      }

    });
  });
</script>

Any idea how to accomplish what I'm asking?

user2943464
  • 57
  • 1
  • 8

3 Answers3

0

I'll give you a nudge in the right direction, but won't supply you the answer outright.

You need to find a way to check the property of your elements visibility ( How do I check if an element is hidden in jQuery? This might help you!), and add that to your conidtion like so:

if(KeyIsPressed && element.IsVisible)
{
HideElement
}
else if(KeyisPressed)
{
ShowElement
}
Community
  • 1
  • 1
  • I tried something along the lines of: if(keyEvent.keyCode == 13 && document.getElementById("hideAnswer").style.visibility == "visible") showAns and something similar for the alternate case but it still wasnt working. I ended up going with nix's answer and it worked. Thank you though – user2943464 Nov 15 '13 at 06:14
0

Without getting too fancy, you can use a 'state' variable to hold that information, and then synchronize that to the DOM:

var state = {
  "div1": true,
  "div2": false,
};

synchronizeState();

$(document).on("keydown", function(event) {
  if(event.which === 13) {
    state.div1 = !state.div1;
    state.div2 = !state.div2;
    synchronizeState();
  }
});

function synchronizeState() {
  if(state.div1) {
    $("#div1").show();
  } else {
    $("#div1").hide();
  }

  if(state.div2) {
    $("#div2").show();
  } else {
    $("#div2").hide();
  }
}

Working example: http://jsbin.com/eJiPavO/1/

Renato Zannon
  • 24,465
  • 6
  • 30
  • 38
0

Try this sample of what you want to achieve:

var toShow = true;
$(document).keydown(function(keyEvent) {
    if(keyEvent.keyCode == 13){
            $('#div1').toggle(toShow);
            $('#div2').toggle(!toShow);
        toShow = !toShow;
    }
});
Nikko Reyes
  • 3,132
  • 2
  • 17
  • 35