1

I'm putting together a succinct jQuery matrix because I'm having a hard time navigating around on the jQuery site, and the cheat sheets don't seem to provide me what I want either.

Here's how I highlight the rows:

$('.eq').hover(function() {
    $('.eq').toggleClass('highlight');
});
$('.is').hover(function() {
    $('.is').toggleClass('highlight');
});

Q: How can I write a function that says "toggle everything in the same class as what is being hovered over"? Something like:

function toggle(that){
    $(that.className).toggleClass('highlight');
}
Phillip Senn
  • 46,771
  • 90
  • 257
  • 373

3 Answers3

2

Did you know that tables can have multiple tbody elements?

Just wrap sets of rows in separate tbody elements. And then we can use:

$('tbody').hover(function() {
    $(this).toggleClass('highlight');
});

And in newer browsers, it can be done using CSS only:

tbody {
    /* Normal style */
}

tbody:hover {
    /* Highlighted style */
}
Community
  • 1
  • 1
PleaseStand
  • 31,641
  • 6
  • 68
  • 95
1

"How can I write a function that says "toggle everything in the same class as what is being hovered over"?"

Elements can have multiple classes, and would you want to do this with every element anyway? A better approach may be to write a plugin for the elements you want, like this:

$.fn.highlightClass = function() {
  return this.hover(function() {
    $("."+this.className.split(" ").join(",.")).toggleClass("highlight");
  });
};

Then you'd call it on the elements you care about, for example:

$(".eq, .is").highlightClass();

If you had for example a class="eq test" element, it'd change it to a ".eq,.test" selector, and toggle the highlight class on all of those elements. Just change the .join() call to .join(".") if you want it to only highlight elements with all the classes of the elements you're hovering, as opposed to any of the classes...like I have above.

Nick Craver
  • 623,446
  • 136
  • 1,297
  • 1,155
1

If you are assigning only one class to the HTML element that is hovered then use this slightly changed version:

function toggle(that){
    $("." + that.className).toggleClass('highlight');
}
Chandu
  • 81,493
  • 19
  • 133
  • 134