views:

304

answers:

4

Can somebody advise me with jQuery selectors.

I have a HTML list (see below) with four flag images in it. When a user rolls over a flag for example italy, I want it to fade out all the other three flags to 50% opacity.

<ul id="flags">
    <li id="German"><img src="images/flag_german.jpg" /></li>
    <li id="Italian"><img src="images/flag_italian.jpg" /></li>
    <li id="Spanish"><img src="images/flag_spanish.jpg" /></li>
    <li id="French"><img src="images/flag_french.jpg" /></li>
</ul>
+5  A: 

What about someting like this (not tested)

   $("#flags li").mouseover(function(){
      var id = this.id;
      $("#flags li").not("#"+id).animate({opacity:'0.5'},1000);
      $(this).animate({opacity:'1'},1000);
    });
mkoryak
$(this).show(); would require less work from JQuery.
John Fisher
Cheers seth... lemme try it out!rgdsD
I just fixed a typo. The solution is all mkoryak
seth
If you roll over all the li's quickly you will see it continue to fade each one even after you have stopped moving the mouse. My answer will work correctly in this case.
PetersenDidIt
Thats great. That is what I was searching for a long time.
sn3ek
A: 

You might want to look into the siblings selector.

Henrik Opel
Thanks everyone! Got it to work, looks great! Can't wait to get up to speed with jQuery! ...it's amazing!Thanks againDecbrad
+10  A: 

Try this:

$(function() {
    $('#flags li').hover(function() {
        $(this).siblings().stop(true).animate({opacity:'0.5'},1000);
    }, function() {
        $(this).siblings().stop(true).animate({opacity:'1'},1000);
    });
});

By using stop you help prevent the state where you have rolled over alot of elements and they have queued up animations. It clears all the current animations in the queue for the element and assigns the new one.

The reason you need to use animate rather then fadeIn and fadeOut is because of a weird bug with fadeIn/fadeOut and the hover event. Haven't figured out what causes the bug though.

PetersenDidIt
+1 for hover and not leaving the elements faded when you stop hovering over the entire collection.
tvanfosson
+1  A: 
$('#flags li').bind('mouseover', function() {
    $('#flags li').not($(this)).fadeTo('fast', 0.5);
}).bind('mouseout', function() {
    $('#flags li').show();
});
Ravish