0
votes

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

1
Do you mean that you don't want to hide if shown and clicked again ? - pc_coder
@pc_coder Yes, so if I complete the action of show/hide by clicking twice - I want the default div to be visible. As opposed to a blank screen - Jordan Miguel
var atLeastOneElemtVisible = false, divs = $('.show'); divs.forEach(elem=>{ if(!elem.style.visiblity('hidden')){ // correct the syntax atLeastOneElemtVisible = true; break; } }); if(!atLeastOneElemtVisible){ $('.default').removeClass('hidden'); } - ABGR
@RahulDwivedi can you add that code as an answer, not a comment. - Jordan Miguel
Sure Just did that. Basically this is the idea: Check if all the show divs are hidden. If Yes, remove the hidden class from your default div. Please excuse me for any syntactical error. - ABGR

1 Answers

1
votes

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)

    });


  })