Fernando Souza Fernando Souza - 3 months ago 11
Javascript Question

Javascript boolean parameter not passing correctly

I created a function with various if statements,that will be executed if a parameter is true. But passing false as a parameter doesn't seem to work. What am I doing wrong?

function easySlider(titleP,subTitleP,overlayP){
var title = titleP;
var subTitle = subTitleP;
var overlay = overlayP;

if(title===true) {
$(".sliderTitle").css("display","block");
}else{
$(".sliderTitle").css("display","none");
}

if(subTitle===true) {
$(".sliderSubTitle").css("display","block");
}else{
$(".sliderSubTitle").css("display","none");
}

if(overlay===true) {
$(".sliderOverlay").css("display","block");
}else{
$(".sliderOverlay").css("display","none");
}
}

easySlider(false,false,false);

Answer

You can try this

<div class="sliderTitle"></div>
<div class="sliderSubTitle"></div>
<div class="sliderOverlay"></div>

<script src="https://code.jquery.com/jquery-1.12.4.min.js"></script>
<script>
    function easySlider(title, subTitle , overlay) {
        var titleDisplay     = title ? 'block' : 'none';
        var subTitleDisplay  = subTitle ? 'block' : 'none';
        var overlayDisplay   = overlay ? 'block' : 'none';

        $(".sliderTitle").css("display", titleDisplay);
        $(".sliderSubTitle").css("display", subTitleDisplay);
        $(".sliderOverlay").css("display", overlayDisplay);
    }

    easySlider(false, false, false);
</script>
Comments