Dadou
Dadou

Reputation: 1008

Add colgroup for each table column

There are probably other similar posts, but here goes nothing.

I am currently reworking on an existing site and some of the changes required involves column and row highlighting, like here (tutorial / demo).

Since there are several web pages to go through, I would like to have some kind of shortcut to dynamically add <colgroup></colgroup> like in the example without having to go through each page and table by hand.

I've considered php's preg_replace function, but I doubt that's the simplest way to go around it. In an optimal scenario, I would be able to verify if there is an existing <colgroup></colgroup> array for each column.

Upvotes: 1

Views: 1719

Answers (1)

Sean
Sean

Reputation: 12433

Using jQuery you could dynamically prepend the <colgroup></colgroup> to each table before your highlight script. Something like -

if($("table > colgroup").length == 0){ // If the table does not have <colgroup></colgroup>

    var colCount = 0;
    $('tr:nth-child(1) td').each(function () { // Get the count of table columns
        if ($(this).attr('colspan')) { // if there is a <td colspan>
            colCount += +$(this).attr('colspan');
        } else {
            colCount++;
        }
    });


    var colgroupList = '';
    for (i=0;i<colCount;i++){ // Add a <colgroup></colgroup> for each <td>
        colgroupList += '<colgroup></colgroup>';
    }


    $("table").prepend(colgroupList);

}

$("table").delegate('td','mouseover mouseleave', function(e) {
 ...

jsFiddle example http://jsfiddle.net/BGR22/1/


Edit
If you have multiple tables on a page, you need to add a selector to only get the parent table -

var $table = $(this).closest("table");

So now your $("table").delegate() would look like

$("table").delegate('td','mouseover mouseleave', function(e) {
   var $table = $(this).closest("table");
   if (e.type == 'mouseover') {
     $(this).parent().addClass("hover");
     $table.children("colgroup").eq($(this).index()).addClass("hover");
   } else {
     $(this).parent().removeClass("hover");
     $table.children("colgroup").eq($(this).index()).removeClass("hover");
    }
});

Updated jsFiddle - http://jsfiddle.net/BGR22/3/
and with 3 tables - http://jsfiddle.net/BGR22/4/

Upvotes: 1

Related Questions