Search code examples
javascriptcsshtml-tabledom-events

Hide table column ondblclick


I have a table and I want to hide a column when I double click a column.

Code for hiding a column is practically all around Stack Overflow. All I need is a hint on how/where to add the ondblclick event so I can retrieve the identity of a <td> within a <table>.


Solution

  • Here are two solutions that should work. One done with jQuery and one with only standard Javascript.

    http://jsfiddle.net/GNFN2/2/

    // Iterate over each table, row and cell, and bind a click handler
    // to each one, keeping track of which column each table cell was in.
    var tables = document.getElementsByTagName('table');
    for (var i = 0; i < tables.length; i++) {
        var rows = tables[i].getElementsByTagName('tr');
        for (var j = 0; j < rows.length; j++) {
            var cells = rows[j].getElementsByTagName('td');
            for (var k = 0; k < cells.length; k++) {
                // Bind our handler, capturing the list of rows and colum.
                cells[k].ondblclick = column_hide_handler(rows, k);
            }
        }
    }
    
    // Get a click handler function, keeping track of all rows and
    // the column that this function should hide.
    function column_hide_handler(rows, col) {
        return function(e) {
            // When the handler is triggered, hide the given column
            // in each of the rows that were found previously.
            for (var i = 0; i < rows.length; i++) {
                var cells = rows[i].getElementsByTagName('td');
    
                if (cells[col]) {
                    cells[col].style.display = 'none';
                }
            }
        }
    }
    

    With jQuery it is much cleaner. This method also uses event bubbling, so you don't need to bind an event handler to each table cell individually.

    http://jsfiddle.net/YCKZv/4/

    // Bind a general click handler to the table that will trigger
    // for all table cells that are clicked on.
    $('table').on('dblclick', 'td', function() {
        // Find the row that was clicked.
        var col = $(this).closest('tr').children('td').index(this);
        if (col !== -1) {
            // Go through each row of the table and hide the clicked column.
            $(this).closest('table').find('tr').each(function() {
                $(this).find('td').eq(col).hide(); 
            });
        }
    });