Phillip Senn
Phillip Senn

Reputation: 47663

Highlight multiple rows using jQuery

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');
}

Upvotes: 1

Views: 1352

Answers (3)

PleaseStand
PleaseStand

Reputation: 32122

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 */
}

Upvotes: 2

Chandu
Chandu

Reputation: 82963

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');
}

Upvotes: 1

Nick Craver
Nick Craver

Reputation: 630637

"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.

Upvotes: 1

Related Questions