Skip to content Skip to sidebar Skip to footer

Javascript For Toggling Visibility Of Table Cell

I have a code which creates html reports. It uses html tables to display the results, the tables are sortable, and they are zebra striped automatically, so there is already Javascr

Solution 1:

Attach an onclick event to the table, and look at the event's target.

table.onclick = function(e) {
    e = e || window.event;
    var target = e.target || e.srcElement;
    while(target != this && (!target.tagName || target.tagName != "TD")) target = target.parentNode;
    if( target != this) {
        // "target" is the cell that was clicked. Do something with it.
    }
}

Side-note: You don't need JavaScript to zebra-stripe the rows. Just use CSS:

tr {background-color:white}
tr:nth-child(even) {background-color:black;}

Solution 2:

If you are looking to learn, jQuery is the way to go. It's a great javascript framework that will make your life much easier as you get more familiar with javascript. jQuery has functionality to do just what you are saying. Check out the docs on toggle().

You would do something like this:

$('td').click(function() {
    $('td').show();
    $(this).toggle();
});

This would 'toggle' the visibility of any TD that you click. Here is a fiddle.

Post a Comment for "Javascript For Toggling Visibility Of Table Cell"