简体   繁体   中英

close hidden div onclick and toggle another div

i am using the following code to toggle hidden divs.

function toggle_visibility(id) {
       var e = document.getElementById(id);

          $(e).slideToggle("slow");




    }

<div id="toplinks">
<a href="../index.php">Home</a> | <a href="#" onclick="toggle_visibility('aboutus');">About Us</a> | <a href="#" onclick="toggle_visibility('contact');" >Contact us</a> | <a href="#" onclick="toggle_visibility('social');">Social Media</a> | <a href="#" onclick="toggle_visibility('contact');">Send your demo</a> | <a href="#" onclick="toggle_visibility('presskit');">Press Kit</a>
</div><!--toplinks end -->

the problem is that if i click on all of them, the would all appear in the page at the same time. is there a way to close automatically one (if its open), so that only one div appears if clicked?

You can save your prev id in variable, and if it not null, make toggle again. For example:

var prevId;

function toggle_visibility(id) {
   if(prevId && id !== prevId){
      $("#"+prevId).slideToggle("slow");
   }
   var e = document.getElementById(id);

      $(e).slideToggle("slow");
   prevId = id;

}

yes.

first of all, add panel css class to each of the panels that suppose to appear and disappear with navigation items click.

secondly, add css class to each <a> tag with it's name (home, aboutus, etc...)

and then use this jQuery code:

$(function(){
    $('#toplinks a').click(function(){
        $('.panel').hide(); // hide all panels
        if ($(this).hasClass('home')) {
            $('.panel.home').fadeIn(); // show homepage panel
        }
        else if ($(this).hasClass('aboutus')) {
            $('.panel.aboutus').fadeIn(); // show about us panel
        }
        // more items ...
    });
});

hope that helped.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM