oliverwebr
oliverwebr

Reputation: 627

Why does this if/else statement always execute the if branch?

Hey guys I know that there exists .slideToggle() but I want to add more features later.

I don't know what I'm doing wrong, sliding up works but I cannot slide down.

Can I not overwrite my var? Would be very nice when somebody can help me.

$(document).ready(function () {

    var resizeValue = true;
    $(".resizeSelect").click(function () {
        if (resizeValue === true) {
            $(".resize").slideUp(

            function () {
                $('.parent').height($('.child').height('100'));
            });
            var resizeValue = false;
        } else {
            $(".resize").slideDown(

            function () {
                $('.parent').height($('.child').height('100'));
            });
            var resizeValue = true
        };
    });
});

Upvotes: 0

Views: 705

Answers (2)

Thobias Karlsson
Thobias Karlsson

Reputation: 96

You shouldn't redefine the resizeValue variable within the click function. Just remove var from var resizeValue (it should only be used at the top of the ready-function).

Upvotes: 8

sdespont
sdespont

Reputation: 14025

Because you are redeclaring your variable resizeValue in your function instead of update it :

$(document).ready(function () {

    var resizeValue = true;
    $(".resizeSelect").click(function () {
        if (resizeValue === true) {
            $(".resize").slideUp(

            function () {
                $('.parent').height($('.child').height('100'));
            });
            //DO NOT DECLARE NEW VARIABLE WITH VAR
            resizeValue = false;
        } else {
            $(".resize").slideDown(

            function () {
                $('.parent').height($('.child').height('100'));
            });
            //DO NOT DECLARE NEW VARIABLE WITH VAR
            resizeValue = true
        };
    });
});

Upvotes: 6

Related Questions