Reputation: 373
I have a group of icons where when you hover over an icon, the other img's in the set fade out. I was able to do this using longer selectors, but I wanted to try using the siblings() selector, but I just can't get it to work. What am I missing here? Thanks
<div id="picks" class="section">
<div class="pick left">
<img src="images/p_mary.jpg" />
<div class="icons">
<a href="#" ><img src="images/i_imdb.png" /></a>
<a href="#" ><img src="images/i_imdb.png" /></a>
<a href="#" ><img src="images/i_imdb.png" /></a>
<a href="#" ><img src="images/i_imdb.png" /></a>
</div>
</div>
</div>
and then the javascript:
$("#picks").find("a > img").hover(function () {
$(this).siblings().stop().fadeTo(0, .3);
$(this).stop().fadeTo(0,1);
}, function () {
$(this).siblings().stop().fadeTo(500, 1);
});
Upvotes: 1
Views: 3454
Reputation: 22395
Like this:
$('.icons > a').hover(function() {
$(this).siblings().stop().fadeTo(300, 0.2);
}, function() {
$(this).siblings().stop().fadeTo(300, 1);
});
Fiddle: http://jsfiddle.net/5jvmK/3/
Using the above technique it will attach an hover event for all the matched elements. If you have a lot of icons on the page the performance could be low. Instead, you could use .delegate
to help increase the performance:
$('.icons').delegate('a', 'hover', function(event) {
if (event.type == 'mouseenter') {
$(this).siblings().stop().fadeTo(300, 0.2);
}
else
{
$(this).siblings().stop().fadeTo(300, 1);
}
});
This will attach an event onto JUST .icons
and will fire on the event on the matched selector a
.
Let's say you had 20 <div class="icons">
each with their own, let's say, 4 icons. With:
.hover
: it'll attach 80 events to the DOM (20*4)..delegate
: it'll attach just 20. That's a 400% increase in performance.Fiddle: http://jsfiddle.net/5jvmK/5/
Upvotes: 2
Reputation: 10572
I think that selector is actually targeting the img try:
$(this).parent().siblings().children().stop().fadeTo(0, .3);
For all possibly try:
var siblings = $(this).parent().siblings();
for(var s = 0; s < siblings.length; s++){
$(siblings[s]).children().stop().fadeTo(0,.3);
}
Upvotes: 2
Reputation: 309
Well the problem with the siblings() function is that it returns siblings on the same level.
if you would do the following for example:
$("#picks").find(".icons a").hover(function () {
$(this).siblings().stop().fadeTo(0, .3);
$(this).stop().fadeTo(0,1);
}, function () {
$(this).siblings().stop().fadeTo(500, 1);
});
This should make the links fade because the "a" tags are on the same level and thus are siblings in the way "siblings()" is working. Using "a > img" selects all img tags ... but none of those have siblings...
Take a look at this code:
<a href="#">
<img src="image.gif" />
<img src="image.gif" />
<img src="image.gif" />
</a>
Here the img tags have siblings ... I hope this is clear enough for you.
Upvotes: 2