FirstOrderKylo FirstOrderKylo - 2 months ago 7
HTML Question

Adding show one a time functionality and slide animation to pre-existing script

So I've got a show/hide script I use on my website that works great. However there's 1 issue and one request.


  1. Need to allow only 1 div at a time to show

  2. When the div appears, to
    have it 'slide' in from underneath the header.



Here's the script:

function toggle_visibility(id) {
var e = document.getElementById(id);
if(e.style.display == 'block')
e.style.display = 'none';
else
e.style.display = 'block';
}


Here is how the buttons work in relation to the div's in the HTML:

<a onclick="toggle_visibility('testing');">Testing</a>

<div style="display:none;" id="testing">
testing for page 2
</div>


Here is the layout of the screen in regards for the slide animation:

enter image description here

If anyone could help with adding these functions to the script or they have a different script that does the same thing but better please let me know.
Thanks

Answer

If you want to go with jQuery, then take a look at slideToggle():

<html>
  <head>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>

    <script>
      var activeDiv = 'welcome';
      function toggle_visibility(id) {            
        if ( activeDiv === id ) return;
        $('#' + activeDiv).css('display','none');
        activeDiv = id;
        $('#' + id).slideToggle();
        $('#' + id).css('display','block');
      };
      $(document).ready(function() {
        $('#welcome').slideToggle();
      });

    </script>
  </head>
  <body>
    <a onclick="toggle_visibility('testing');">Show the First DIV</a><br>
    <a onclick="toggle_visibility('testing2');">Show the Second DIV</a>

    <div style="display: none;" id="testing">
      The First DIV
    </div>

    <div style="display: none;" id="welcome">
      Welcome!
    </div>

    <div style="display: none;" id="testing2">
      The Second DIV
    </div>
  </body>
</html>