Forums

The forums ran from 2008-2020 and are now closed and viewable here as an archive.

Home Forums JavaScript Multiple Table Cells Change Background On Hover

  • This topic is empty.
Viewing 5 posts - 1 through 5 (of 5 total)
  • Author
    Posts
  • #174164
    jp23
    Participant

    I built a mockup table where one cell is hovered over, all the other cells not in the same class change opacity. Basically, on hover, all the cells in that class stand out. Here’s a link to the finished mockup: http://jsfiddle.net/4KK3b/.
    I’m fairly good at coming up with the extra long form code. I’m guessing there’s a more efficient way. So my question, is there a better way to write this? If so, does anyone know of a resource steer me in the right direction?

    Thanks

    #174183
    Paulie_D
    Member

    I’m no expert in Jquery but I managed to noodle it out a little.

    First, we really don’t want to have to repeat ourselves but by using Jquery’s $this we can capture the class of our selected object.

    Then, once we have that class we can define it as a variable, combine it with the :not selector to select everything that is not the same class as our original object.

    $(document).ready(function(){
    $(“td”).mouseover(function(){
    var myClass = $(this).attr(“class”);
    $(“td:not([class=”+ myClass +”])”).css(“opacity”,”0.4″);
    });

    $(“td”).mouseout(function(){
    var myClass = $(this).attr(“class”);
    $(“td:not([class=”+ myClass +”])”).css(“opacity”,”1″);
    });

    });

    JSfiddle Demo

    #174298
    jp23
    Participant

    This is a lot more than I expected and a huge help compared to what I was doing.

    Thanks Paulie_D! You’re an expert in my book :)

    #174299
    Senff
    Participant

    Not to diss Paulie’s solution, I would personally do it a little different with less code: http://codepen.io/senff/pen/Cyief

    Basically, same idea of checking the class first on hover. Then “dimming” all cells that simply don’t have the same class as the cell that’s being hovered on:

    $('td').hover(function() {
      theClass=$(this).attr('class');
      $('td:not(.'+theClass+')').addClass('dim');
    }, function() {
      $('td').removeClass('dim');
    });
    
    #174349
    Paulie_D
    Member

    Yeah, I considered using .hover but I assume there was a reason for the mouseOver/mouseOut.

    And, of course, the add/remove class is the preferred way of doing it in my book but, again, I didn’t want to introduce more complexity.

    As I said, I’m no JQuery expert…I cut & paste and refer to the API notes to figure it out but one thing I have found..there are usually several ways to do anything.

Viewing 5 posts - 1 through 5 (of 5 total)
  • The forum ‘JavaScript’ is closed to new topics and replies.