Search code examples
javascriptjqueryhideshow

jQuery check if element is visible in if statement not working


I need a function that displays only one of the selected divs at a time. I have it pretty much working except the if statement. I want the button to hide the div if it is already showing. But it is not working and I cant figure out why. Thank you for your help.

jQuery(function() {
  jQuery('.showSingle').click(function() {
    jQuery('.targetDiv').hide();
    if (jQuery('#div' + $(this).attr('target')).is(":visible")) {
      jQuery('.targetDiv').hide();
    } else {
      jQuery('#div' + $(this).attr('target')).slideToggle();
    }
  });
});
.targetDiv {
  display: none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button class="showSingle" target="1">Div 1</button>
<button class="showSingle" target="2">Div 2</button>
<button class="showSingle" target="3">Div 3</button>
<button class="showSingle" target="4">Div 4</button>
<div id="div1" class="targetDiv">Lorum Ipsum1</div>
<div id="div2" class="targetDiv">Lorum Ipsum2</div>
<div id="div3" class="targetDiv">Lorum Ipsum3</div>
<div id="div4" class="targetDiv">Lorum Ipsum4</div>


Solution

  • The first line of your function is hiding all the DIVs:

    $(".targetDiv").hide();
    

    So when it tests whether the target DIV is visible, it's not, because you just hid it. You should hide all the DIVs except the target:

    $(".targetDiv:not(#div"+$(this).attr("target")+")").hide();
    

    jQuery(function() {
      jQuery('.showSingle').click(function() {
        var targetID = '#div' + $(this).attr('target');
        jQuery('.targetDiv:not('+targetID+')').hide();
        if (jQuery(targetID).is(":visible")) {
          jQuery('.targetDiv').hide();
        } else {
          jQuery(targetID).slideToggle();
        }
      });
    });
    .targetDiv {
      display: none;
    }
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <button class="showSingle" target="1">Div 1</button>
    <button class="showSingle" target="2">Div 2</button>
    <button class="showSingle" target="3">Div 3</button>
    <button class="showSingle" target="4">Div 4</button>
    <div id="div1" class="targetDiv">Lorum Ipsum1</div>
    <div id="div2" class="targetDiv">Lorum Ipsum2</div>
    <div id="div3" class="targetDiv">Lorum Ipsum3</div>
    <div id="div4" class="targetDiv">Lorum Ipsum4</div>