Robert
Robert

Reputation: 58

How would I animate several elements with an if/else

Maybe I am approaching this wrong, and if that is the case please don't hesitate to tell me so.

My question is related to having several div's in a 4x3 pattern wrapped in a container element. The goal is to hover over one element, assign it a class, and make it bigger while making all other div's in the container are made smaller and have no class.

    $("#portChoose > div").hover(function () {
    $(this).addClass("onTarget");
    if( $(this).hasClass("onTarget") ){
        $(this).animate({"width": "40px","height": "40px"}, 100);
    } else {
        $("#portChoose > div").animate({"width": "30px","height": "30px"}, 100);
    }
}, function(){
   $(this).removeClass("onTarget");                
});

Would this be the correct way to go about doing this sort of thing? If not, which would be the best way to approach this type of scenario?

I have linked what I had though would work but am achieving no luck. Any help or even insight would greatly be appreciated. Thanks!

JSFiddle: http://jsfiddle.net/rlvassallo/wyjf5/

Upvotes: 0

Views: 32

Answers (1)

Liftoff
Liftoff

Reputation: 25392

If you want to do something to just one div and something else to all of the others, you can call them as siblings if they are children to the same element. For instance:

$("#portChoose > div").hover(function(){
    $(this).animate({

        //Animate the hovered element

    }, 100).siblings("div").animate({

        //Animate the others

    }, 100);
});

JSFiddle

As you can see in the JSFiddle, I also added a mouseOut call to shrink the hovered div as well as a call to .stop() before each animation call to terminate any running animations.

Upvotes: 1

Related Questions