bbruman
bbruman

Reputation: 677

Hide/Show DIV on KeyPress Not Working jQuery

Confused as to why jQuery is understanding my logic but not functioning off the show() and hide() on selected DIVs on keypress (yet works to hide() on page load).

Here's the script which is at the end of my PHP page.

<script>
jQuery(function(){

        $("#resultset_2").hide();
        $("#resultset_3").hide();

// this is working -- `#resultset_2` and `#resultset_3`
// are both set to "display:none;" on page load

    $(document).keydown(function (e) {

    var keyCode = e.keyCode || e.which,
      arrow = {left: 37, up: 38, right: 39, down: 40 };

    switch (keyCode) {
    case arrow.left:
      // tbd
    break;
    case arrow.up:
      // tbd
    break;
    case arrow.right:
      // tbd
    break;

    case arrow.down:

    if($('#resultset_1').is(':visible')){

        alert('visible');
        $("#resultset_1").hide();
        $("#resultset_2").show();

    }

    if($('#resultset_2').is(':visible')){

        $("#resultset_2").hide();
        $("#resultset_3").show();

    }
    if($('#resultset_3').is(':visible')){

        $("#resultset_3").hide();
        $("#resultset_1").show();

    }
    break;
    }
    });
});
</script>

Keypress functionality is working, so I know that's not an issue. When I press down on my keyboard I get the alert 'visible' pop-up indicating that $resultset_1 is visible.

But nothing happens after that, jQuery ignores the $("#resultset_1").hide(); and $("#resultset_2").show(); in my condition.

I've tried variations, such as

   if($('#resultset_1').is(':visible')){
        alert('visible');
        $('#resultset_1').css('display','none');
    }

With the same result (an alert but an ignore on the div change)

Why is this not functioning properly and how do I fix it to work as defined? Working with a minified jQuery v3.3.1

Upvotes: 0

Views: 330

Answers (1)

Ian Woodfill
Ian Woodfill

Reputation: 164

In the if statement with your alert you unhide #resultset_2 and therefore the second if statement executes and #resultset_2 is hidden once again and #resultset_3 is shown. The same thing happens with the next if statement, hiding #resultset_3 and showing #resultset_1 again. You should make the second two if statements else if statements.

Upvotes: 1

Related Questions