jQuery plugin to change the row color on hover

For my project CivCRM, I wrote a simple jquery plugin to change the row color on mouse hover. It is generic enough and can be used in any project. Here is the implementation.

1. Create a plugin file: jquery.crmrowhighlighter.js

(function($){ $.fn.crmrowhighlighter = function(){

if ($(‘.crm-row-highlighter-processed’).length == 0){

$(‘.selector tr’).hover(function(){

$(this).addClass(‘crm-row-highlight’);

},function(){

$(this).removeClass(‘crm-row-highlight’);

});

$(‘.selector’).addClass(‘crm-row-highlighter-processed’);

};

};

})(jQuery);

2. Create css file: my.css

.crm-row-highlight {

background-color: #FFFFCC !important;

}

Usage:

<script type=”text/javascript” src=”jquery.js”></script>

<script type=”text/javascript” src=”jquery.crmrowhighlighter.js”></script>

<style type=”text/css”>@import url(“my.css”);</style>

<table class=”selector”>

<tr> Row 1: Hover to change the color</tr>

<tr> Row 2: Hover to change the color</tr>

</table>

<script type=”text/javascript”>

$( function(){

$().crmrowhighlighter( );

});

</script>

Note: You need to have table’s class = “selector”

That’s it, now when you hover the row color will change. Hope this helps.

6 thoughts on “jQuery plugin to change the row color on hover”
  1. Hi,

    Instead of hardcoding on .selector,
    do call

    $(‘.selector’).crmrowhighlighter( );

    and modify the plugin so

    (function( $ ){

    $.fn.crmrowhighlighter = function() {

    this.find(‘tr’).hover(function(){

    $(this).addClass(‘crm-row-highlight’);

    },function(){

    this.removeClass(‘crm-row-highlight’);

    });

    this.addClass(‘crm-row-highlighter-processed’);

    To make it really generic, crm-row-highlight should be an optional param to the function
    $(‘.selector’).crmrowhighlighter( {highlighted: ‘.crm-row-highlight’}); //but I’m being picky 😉

    X+

    P.S. Not quite sure what is the aim of .crm-row-highlighter-processed. Extra css styling ?

  2. Actually selector class i.e. “selector” and highlighting class i.e “crm-row-highlight” both should be params. That would be good addition 🙂

    We can’t use ” this.find(‘tr’)…. ” because a page can have multiple tables and you don’t want to on hover highlight all tables.. hence we need to define class.

    Does this make sense ..

  3. this.find(“tr”) only applies to the children of the table selected, so it works.

    The .selector isn’t a “real” param, but the selector where you apply the plugin to be in the jQuery spirit. Take my code example, should work straight out of the box.

    yeap, the crm-row-highlighter is a param. You can use extend for that (what is used for instance on crmAPI)

    X+

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.