Welcome to the Treehouse Community
Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.
Looking to learn something new?
Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.
Start your free trial
Michael Crawbuck
11,026 PointsIF data attribute matches element ID
Hello all,
Working on a small mouseover function that when you hover a list item that has a data attribute named data-id, a div outside the list with an ID that matches the list items data attribute. So for example: <div id="post-1" class="project-img"></div> <ul> <li data-id="post-1">Listem Item</li> </ul>
So essentially, I'm trying to do a mouseover function where on mouseover of the list item, IF the div ID matches the data-attribute, add a class called active. Here's what I have so far but I can't seem to get it right?
$('#work ul li').on('mouseover', function() {
var postHovered = $(this).data("id");
$('.project-img').each(function(){
if($(this).attr('id') === postHovered) {
$(this).addClass('active');
} else {
$(this).removeClass('active');
}
});
});
Any insight would be extremely helpful. Thank you in advance.
Michael Crawbuck
11,026 PointsOh shoot! Thank you for that. You made me realize that I was only getting "1","2","3", etc. When the id on my div was "post-1","post-2","post-3", etc. Silly oversight. Thank you for that.
1 Answer
Steven Parker
243,160 PointsIt seems to work for me.
I'm not sure why your names were getting "decapitated" like you describe. I tried it and it seemed to work just fine for me. But your HTML sample wasn't complete .. I had to add a bit to it. Perhaps something was different there?
Dan Oswalt
23,438 PointsDan Oswalt
23,438 PointsWhat do you get when you console.log(postHovered)?