Search code examples
javascriptjquerytoggleshow-hide

jQuery toggle show/hide default content


I have a show/hide toggle that switches between content if menu a is clicked.

Before the click function is triggered content is shown in the default div.

For some reason if you click one of the a tag's twice it successfully toggles the content on/off; however you are left with a blank screen

This is a poor user experience.

How can I avoid this and ensure that the default content is shown if a user selects a menu item twice?

$(document).ready(function() {
  var $show = $('.show');

  $('.menu a').on('click', function(e) {
    e.preventDefault();
    $show.not(this).stop().hide(450);
    $($(this).attr('href')).stop().toggle(450);
    $('.default').addClass('hidden');
  });


});
.hidden {
  display: none;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<div class="menu">
  <a href="#show-screen">Screen</a>
  <a href="#show-music">Music</a>
  <a href="#show-art">Art</a>
  <a href="#show-food">Food</a>
</div>

<div id="show-screen" class="show">show screen</div>
<div id="show-music" class="show">show music</div>
<div id="show-art" class="show">show art</div>
<div id="show-food" class="show">show food</div>

<div class="default">default content</div>

Thanks


Solution

  • Although I'd suggest a completely different approach to handle this problem, to make your code work, I'd do something like this. https://jsfiddle.net/6cnt95ap/1/

    $(document).ready(function() {
      var $show = $('.show');
      $('.menu a').on('click', function(e) {
        e.preventDefault();
        $show.not(this).stop().hide(450);
        $($(this).attr('href')).stop().toggle(450);
        $('.default').addClass('hidden');
    
      window.setTimeout(()=>{
            var showDefault = true, divs = $('.show');
         divs.each(function(){
           if($(this).css("display") !=='none'){
                showDefault = false;
                return false;
              }
        });
        if(showDefault){
              $('.default').removeClass('hidden');  
         }
      }, 500)
    
        });
    
    
      })