user1469270
user1469270

Reputation:

Problems with jQuery if statement

I am trying to create a simple if statement: if .information-overlay has the CSS property display:block, add background-color:blue;; to body. If not, don't.

HTML:

<div class="information">Information</div>
<div class="work">Work</div>
<div class="information-overlay">INFORMATION OVERLAY</div>
<div class="work-overlay">WORK OVERLAY</div>

CSS:

.information-overlay, .work-overlay {
    display:none;
    width: 300px;
    height: 300px;
    background-color: salmon;
}

JS:

$('.information').click(function () {
    $('.information-overlay').fadeToggle();
    $('.work-overlay').fadeOut();
    if ($('.information-overlay').css('display') == 'block') {
        $('body').css('backgroundColor', 'blue');
    }
    if ($('.information-overlay').css('display') == 'none') {
        $('body').css('backgroundColor', 'white');
    }
});

This works fine, however it does not set the body back to background-color: white; when the toggle fades out (or is call the second if again). It is stuck on blue. Does anyone know how to fix this?

Here is a JSFIDDLE: http://jsfiddle.net/hWXeM/6/

Upvotes: 2

Views: 228

Answers (2)

Praveen
Praveen

Reputation: 56501

Instead add the if..else.. statement inside the fadeToggle like this

$('.information-overlay').fadeToggle( function() {
        if ($('.information-overlay').css('display') == 'block') {
        $('body').css('backgroundColor', 'blue');
    } else if ($('.information-overlay').css('display') == 'none') {
        $('body').css('backgroundColor', 'white');
    }
    });

Check this JSFiddle

Upvotes: 2

Satpal
Satpal

Reputation: 133403

You have to pass action to be performed once the animation is complete

$('.information').click(function () {
    $('.information-overlay').fadeToggle(function () {
        if ($('.information-overlay').css('display') == 'block') {
            $('body').css('backgroundColor', 'blue');
        }
        if ($('.information-overlay').css('display') == 'none') {
            $('body').css('backgroundColor', 'white');
        }
    });
    $('.work-overlay').fadeOut();
});

Demo: http://jsfiddle.net/hWXeM/7/

Upvotes: 3

Related Questions