Friday, July 01, 2011

Making rows in a table appear (or disappear) with HTML and javascript

I ran into this problem and found someone else's solution, so you don't have to.

As luck would have it, I searched on "toggle visibility javascript" and clicked on the first thing I saw: http://blog.movalog.com/a/javascript-toggle-visibility/, which has this fragment:

<script type="text/javascript"><!--
    function toggle_visibility(id) {
       var e = document.getElementById(id);
       if(e.style.display == 'block')
          e.style.display = 'none';
       else
          e.style.display = 'block';
    }
//-->
</script>
This code made my table rows disappear all right, but when I asked them to re-appear, it looked awful. If my table looked like this
row 1something1
row 2something2
row 3something3
row 4something4
and I made, say, rows 2 and 4 disappear, and reappear, with the above code, it looked like this:
row 1something1
row 2something2
row 3something3
row 4something4

Yow! That sure was icky. I discovered some other website that mentioned the concept of using display "inline", but the result still looked like this:

row 1something1
row 2something2
row 3something3
row 4something4

Was there some other "display" I could give it, that would make things look better? I went to htmlhelp.com, which didn't help me much; http://www.htmlhelp.com/reference/css/classification/display.html lists these values:

  • block (a line break before and after the element)
  • inline (no line break before and after the element)
  • list-item (same as block except a list-item marker is added)
  • none (no display)
The secret, as it turns out, was to change the above code to instead look like this:
<script type="text/javascript"><!--
    function toggle_visibility(id) {
       var e = document.getElementById(id);
       //if(e.style.display == 'block') ← not "block"; check vs. 'none' instead
       if(e.style.display != 'none')
          e.style.display = 'none';
       else
          //e.style.display = 'block'; ← no "block" needed; make it empty instead
          e.style.display = '';
    }
//-->
</script>

Which is what the second site in the search results would have told me right away: http://www.dustindiaz.com/seven-togglers/ has:

function toggle(obj) {
 var el = document.getElementById(obj);
 if ( el.style.display != 'none' ) {
  el.style.display = 'none';
 }
 else {
  el.style.display = '';
 }
}

1 comment:

Life Ray said...

That does not work on Google Chrome!