Kevin Mogi
Kevin Mogi

Reputation: 117

Efficient way to check data toggle

var navbarCollapse = true;

var main = function() {
    $('.navbar-toggle').click(function() {
        if (navbarCollapse == true) {
            $('.container').animate({ marginTop: '+300px' }, 400);
            navbarCollapse = false;
        } else {            
            $('.container').animate({ marginTop: '40px' }, 400);
            navbarCollapse = true;
        }
    });
};

Is there another way that more efficient to check if navbar collapse is collapsed or not rather than using variable?

Upvotes: 1

Views: 666

Answers (1)

Rory McCrossan
Rory McCrossan

Reputation: 337610

You can just check the current margin-top value and use a ternary expression to set it based on that. Try this:

var main = function() {
    $('.navbar-toggle').click(function() {
        var $container = $('.container');
        var currentMargin = parseInt($container.css('margin-top'), 10);
        $container.animate({ 
            marginTop: currentMargin == 40 ? '+300px' : 40;
        });
    });
};

Better still, set the margin in a class with a transition rule to cover the animation and then toggle that on and off in your JS:

.container {
    margin-top: 40px;
    transition: margin 0.4s;
}
.container.expand {
    margin-top: 340px;
}
var main = function() {
    $('.navbar-toggle').click(function() {
        $('.container').toggleClass('expand');
    });
};

Upvotes: 1

Related Questions