Kay Kay - 1 month ago 7
Javascript Question

If/Else Statement does not run the else

Here is my JSFiddle:

I am struggling with my If/Else statement. I cannot get the else part of the statement to run. I assume it is something with the ordering... but nothing I try has been helping.

What I want to happen: click the pink button and the small pink appears. click the green button the little green box appears and the pink disappears.

Here is the HTML:

<div id="pport01"></div>
<div id="pport02"></div>
<div class="p01"></div>
<div class="p02"></div>


Here is the css:

#pport01{
position:relative;
display: inline-block;
width: 100px;
height:100px;
background-color: pink;
cursor: pointer;
}

#pport02{
position:relative;
display: inline-block;
width: 100px;
height:100px;
background-color: green;
cursor: pointer;
}

.p01{
position:relative;
display: none;
width: 10px;
height:10px;
background-color: pink;
display: none;

}

.p02{
position:relative;
display:none;
width: 10px;
height:10px;
background-color: green;
}


Here is the JS:

var active01 = false;
var active02 = false;

$('#pport01').click(function(){
active02= false;
active01 = true;
if(active01){
console.log(active01 + "port1 true");
$('.p01').fadeIn("slow");
}else{
console.log(active01 + "port1 false");
$('.p02').fadeOut("slow");
}
});

$('#pport02').click(function(){
active01 = false;
active02 = true;
if(active02){
console.log(active02 + "port2 true");
$('.p02').fadeIn("slow");
}else{
console.log(active02 + "port2 false");
$('.p02').fadeOut("slow");
}
});


It turns out I did not want the if/else statement there. Thank you everyone for your help!
It works now!

Answer

According to your code:

$('#pport01').click(function(){
    active02= false;

// active01 is set to true before the IF

    active01 = true;
    if(active01){
        console.log(active01 + "port1 true");
        $('.p01').fadeIn("slow");
    }else{
        console.log(active01 + "port1 false");
        $('.p02').fadeOut("slow");
    }
});

active01 will always be true when the if is resolved, so the else will never be evaluated. You should rethink what you intend to achieve.

Maybe you don't need the if:

$('#pport01').click(function(){
        $('.p01').fadeIn("slow");
        $('.p02').fadeOut("slow");
});

$('#pport02').click(function(){
        $('.p02').fadeIn("slow");
        $('.p01').fadeOut("slow");
});
Comments