Jquery / JS hover / highlight on table with rowspan

I’d been asked to add a hover highlight feature to a table row which seemed relatively straightforward until I realised that there were ‘rowspan’s peppered through the table.  To add a little further complication the rows had a style applied to them for even and odd rows and the odd row styling was interfering with the highlight.

A straightforward style sheet implementation wouldn’t work because of the multiple rows within effectively one row but a Jquery delegate and some checking of ‘sibling’ rows gave me just what I needed.

CSS for the highlight (I didn’t pick the colour)

.highlight .highlightOdd {
    background-color : #ff5;
}

Javascript which sets the delegate on the table rows and the highlighting / unhighlighting

 function enableTableHighlighting() {
    $("table").delegate('tr', 'mouseover mouseleave', function(e)
    {
        if (e.type == 'mouseover')
        {
            if ($(this).hasClass("odd"))
            {
                setElementAndSiblingHighLight($(this), "odd", "highlightOdd");
            }
            else
            {
                setElementAndSiblingHighLight($(this), "", "highlight");
            }
        } else {
            if ($(this).hasClass("highlightOdd"))
            {
                setElementAndSiblingHighLight($(this), "highlightOdd", "odd");
            }
            else
            {
                setElementAndSiblingHighLight($(this), "highlight", "");
            }
        }
    });
}

Now two functions which allow the individual element’s class to be set as well as any siblings (next and prev)

function switchElementClass(element, oldClass, newClass){
    if (element.hasClass(oldClass)){
        element.removeClass(oldClass);
        element.addClass(newClass);
    }
}

function setElementAndSiblingHighLight(element,oldClass, newClass){
    switchElementClass(element, oldClass, newClass);
    switchElementClass(element.next(), oldClass, newClass);
    switchElementClass(element.prev(), oldClass, newClass);
}
Advertisements

Leave a Reply

Please log in using one of these methods to post your comment:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s