Show / Hide JavaScript Tab

First of all, I want to hide all the content, and then click on one tab, display the corresponding content (the tab will become active), where click it again, it will disappear. some of the tabs are just a mailto link.

The problem is that I cannot hide the tabs when I click again

    $(document).ready(function(){
    $('#nav div').hide();
    $('#nav div:first').show();
    $('#nav ul li:first').addClass('active');
    $('#nav ul li a').click(function(){ 
        $('#nav div').hide();
        $('#nav ul li').removeClass('active');
        $(this).parent().addClass('active'); 
        var currentTab = $(this).attr('href'); 
        if($(currentTab).css('display')=='none'){
            $(currentTab).show();
        }else{
            $(currentTab).hide();
        }

    }
);
});

The navigation code is as follows:

<div id="nav">
    <ul>
      <li><a href="#about">About</a></li>
      <li><a href="mailto:email">Email</a></li>
      <li><a href="#contact">Contact</a></li>
    </ul>
    <div id="about">
      about
    </div>
    <div id="contact">
      contact
    </div>
</div>
+3
source share
3 answers

This should work:

$(function() {
    $('#nav div').hide();
    $('#nav div:first').show();
    $('#nav ul li:first').addClass('active');
    $('#nav ul li a').click(function(){
        var currentTab = $(this).attr('href');
        var vis = $(currentTab).is(':visible');
        $('#nav div').hide();
        $('#nav ul li').removeClass('active');
        $(this).parent().addClass('active');
        if(vis) {
            $(currentTab).hide();
        } else {
            $(currentTab).show();
        }
    });
});

you need to check if the current tab is displayed before which you are hiding.

working: http://jsfiddle.net/tqhHA/

+2
source

Change the click function to:

$('#nav ul li a').click(function(){ 
    var currentTab = $(this).attr('href');  
    $('#nav div').not(currentTab).hide();
    $('#nav ul li').removeClass('active');
    $(this).parent().toggleClass('active');     
    if (currentTab.indexOf("mailto:") === -1)
    {
        $(currentTab).toggle();
    }
});

+1
   $(document).ready(function(){
$('#nav div').hide();
$('#nav div:first').show();
$('a').click(function(){    
    var currentTab = '#'+$(this).text().toLowerCase();
    if($(currentTab).is(':visible')){
        $('#nav div').hide();
        $(currentTab).hide();
    }else{
        $('#nav div').hide();
        $(currentTab).show();
    }
}
);
});


<div id="nav">
    <ul>
      <li><a href="#">About</a></li>
      <li><a href="#">Email</a></li>
      <li><a href="#">Contact</a></li>
    </ul>
    <div id="about">
      about
    </div>
    <div id="contact">
      contact
    </div>
</div>

Please try the code above .. I only change the href value to "#", then some changes in jquery. Please ask in the comments if you have any doubts. click here to check

+1
source

All Articles