nickff
nickff

Reputation: 268

jquery - fade out all children except child being hovered

Trying to do something fairly simple, but it's eluding me. I have the following HTML:

<div id="four">
                <div id="thumb1" class="suiting-thumb">
                    <img src="img/gallery/suit1-thumb.jpg" alt="" title="" />
                </div>


               <div id="thumb2" class="suiting-thumb">
                    <img src="img/gallery/suit2-thumb.jpg" alt="" title="" />
                </div>


               <div id="thumb3" class="suiting-thumb">
                    <img src="img/gallery/suit3-thumb.jpg" alt="" title="" />
                </div>
</div>

All I would like to do is "dim" the children of the parent div, EXCEPT for the child being hovered. I'm successfully doing so with this jQuery snippet, but there is a brief delay between the fade out / in:

$('.suiting-thumb').hover(function() {
                var thumbBtnIdPrefix = 'thumb';
                var thumbBtnNum = $(this).attr('id').substring((thumbBtnIdPrefix.length));
                $('.suiting-thumb:not(#thumb' + thumbBtnNum + ')').animate({
                    "opacity": .3
                }),200;             
            },
            function() {
                $('.suiting-thumb').animate({
                    "opacity": 1
            }),200;
        });

I feel as though I need to be fading out all the children of the parent div by selecting #four with my hover statement, but I'm not quite sure how to do that. Any help would much appreciated, thanks!

Upvotes: 0

Views: 4085

Answers (2)

Mac_Cain13
Mac_Cain13

Reputation: 3633

This should do the trick:

$('.suiting-thumb').hover(function() {
                $('.suiting-thumb').not(this).animate({
                    "opacity": .3
                },200);

                $(this).animate({
                    "opacity": 1
                },200);
        });

This way the animations are executed in parallel. I've also optimized the selector somewhat to make it more readable and animate only the elements that need animation.

Note that you need to wait for a hover animation to finish before the next one starts. If you want that to be instant, make sure calling $('.suiting-thumb').stop(true, false) to stop all animations immediately and then start the next animation.

Upvotes: 0

DarthJDG
DarthJDG

Reputation: 16591

The problem is that you're adding new commands to the animation queue. You have to call stop() which stops all ongoing animations and immediately starts the new one.

$('.suiting-thumb').hover(function() {
    var thumbBtnIdPrefix = 'thumb';
    var thumbBtnNum = $(this).attr('id').substring((thumbBtnIdPrefix.length));
    $('.suiting-thumb:not(#thumb' + thumbBtnNum + ')').stop().animate({
        "opacity": .3
    }), 200;
}, function() {
    $('.suiting-thumb').stop().animate({
        "opacity": 1
    }), 200;
});

http://jsfiddle.net/ywUUL/1/

Upvotes: 5

Related Questions