Home › Forums › JavaScript › Multiple Table Cells Change Background On Hover
- This topic is empty.
-
AuthorPosts
-
June 30, 2014 at 5:49 pm #174164
jp23
ParticipantI 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
June 30, 2014 at 11:24 pm #174183Paulie_D
MemberI’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″);
});});
July 1, 2014 at 6:33 pm #174298jp23
ParticipantThis 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 :)
July 1, 2014 at 7:02 pm #174299Senff
ParticipantNot 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'); });
July 2, 2014 at 7:21 am #174349Paulie_D
MemberYeah, I considered using
.hover
but I assume there was a reason for themouseOver/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.
-
AuthorPosts
- The forum ‘JavaScript’ is closed to new topics and replies.