user2859646
user2859646

Reputation: 83

Jquery If/Then in Click Function?

This is what I want it to do...

When div called 'bd' is clicked > check if the div with id of 'ump' has a class of 'active' > if it does, get div with class of 'brandDump' and slide it up slowly, hide it, and remove the class of 'active' > else, take the div with class 'brandDump' and slide it down, show it, and add class of 'active'

Nothing is happening when I click div.bd. What am I doing wrong?

Fiddle link and code below.

http://jsfiddle.net/K2V8f/36/

<div class="bd">cool</div>
<div class="brandDump" id="ump">works</div>
<div>shape</div>

.brandDump {
background-color:#fff;
width:100px;
display:none;
}

.bd {
width:100px;
height:100px;
background-color:#000;
}

$(".bd").click(function () {
if ("#ump".hasClass("active")) {
    $(".brandDump").slideUp("slow");
    $(".brandDump").hide();
    $(".brandDump").removeClass("active");
} else {
    $(".brandDump").slideDown("slow");
    $(".brandDump").show();
    $(".brandDump").addClass("active");
}
});

Upvotes: 0

Views: 2968

Answers (2)

VVV
VVV

Reputation: 7603

Updated fiddle

You need to use callbacks when the slideUp finishes.

$(".bd").click(function () {
    if ($("#ump").hasClass("active")) {
        $(".brandDump").slideUp("slow", function () {
            $(".brandDump").removeClass("active");
        });

    } else {
        $(".brandDump").slideDown("slow", function () {
            $(".brandDump").addClass("active");
        });

    }

});

Also there was an error with ("#ump")... should have been $("#ump")

Upvotes: 2

nnnnnn
nnnnnn

Reputation: 150080

The problem is that you had:

"#ump".hasClass(...

...when you should've had:

$("#ump").hasClass(...

But note also that the .slideUp() and .slideDown() methods hide and show your element(s) so you don't need to call .hide() and .show() as well. Also it is more efficient to chain jQuery methods together if you want them to operate on the same element:

$(".bd").click(function () {
    if ($("#ump").hasClass("active")) {
        $(".brandDump").slideUp("slow")
                       .removeClass("active");
    } else {
        $(".brandDump").slideDown("slow")
                       .addClass("active");
    }
});

Demo: http://jsfiddle.net/K2V8f/50/

"check if the div with id of 'ump' has a class of 'active' > if it does, get div with class of 'brandDump' and slide it up slowly"

The div with id ump is the same div as the one with class brandDump. I'm not sure why you're talking about them as if they're two different divs when in fact your code seems to then use the #ump and .brandDump selectors interchangeably to select the one div, but if you treat them as one more consistently you can cut your function down to one line:

$(".bd").click(function () {
    $(".brandDump").slideToggle("slow").toggleClass("active");
});

Demo: http://jsfiddle.net/K2V8f/51/

Upvotes: 1

Related Questions