Jack Vawdrey Jack Vawdrey - 2 months ago 18
HTML Question

Toggle visibility with click on original element or another element

So I have a function that makes an element visible when called:



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

<a class="button" href="#" onclick="toggle_visibility('first');">Button</a>
<a class="url" id="first" href="#">First</a>
<a class="button" href="#" onclick="toggle_visibility('second');">Button2</a>
<a class="url" id="second" href="#">Second</a>





And that works, but what I want is for an element to toggle off if I use the function for a different id. So if I first toggle on #first but then toggle on #second I want #first to toggle off.

Answer

Try this:

var lastId = null;
function toggle_visibility(id) {
      if (lastId && id != lastId) {
          var lastEl = document.getElementById(lastId);
          lastEl.style.display = 'none';
      }
      lastId = id;
      var e = document.getElementById(id);
      if(e.style.display == 'block')
         e.style.display = 'none';
      else
         e.style.display = 'block';
      }
<a class="button" href="#" onclick="toggle_visibility('first');">Button</a>
<a class="url" style='display:block' id="first" href="#">First</a>
<a class="button" href="#" onclick="toggle_visibility('second');">Button2</a>
<a class="url" style='display:block' id="second" href="#">Second</a>

Comments