Zac Grierson
Zac Grierson

Reputation: 665

JavaScript - Adding a Class when window is below 750px;

Im using bootstrap 3 and want to make my buttons drop down to btn-sm by adding the btn-sm class to the class list on the anchor.

Here is what im trying.

(function ($) {
    var $window = $(window),
        $btn = $('btn');

    function resize() {
        if ($window.width() < 750) {
            return $btn.addClass('btn-sm');
        }

        $btn.removeClass('btn-sm');
    }

    $window.resize(resize)
        .trigger('resize');
})(jQuery);

So far its failed.

Upvotes: 0

Views: 151

Answers (4)

meni181818
meni181818

Reputation: 1101

you need to 'select' like that:

$(window).resize(function() {
    if($(window).width() < 750) {
        $(".btn").addClass("btn-sm");
    } else if($(window).width() > 750) {
        $(".btn").removeClass("btn-sm");
    }
});

demo: http://jsfiddle.net/cTh57/

Upvotes: 0

DavidG
DavidG

Reputation: 119206

Just use a CSS media query instead and let the browser do the hard work:

@media screen and (max-width: 749px) {
    .btn {
        padding: 5px 10px;
        font-size: 12px;
        line-height: 1.5;
        border-radius: 3px;
    }
}

Upvotes: 1

Daniel Apt
Daniel Apt

Reputation: 2658

First add the class, then use return

(function ($) {
    var $window = $(window),
    $btn = $('btn');

    function resize() {
        if ($window.width() < 750) {
            $btn.addClass('btn-sm');
            return;
        }

        $btn.removeClass('btn-sm');
    }

    $window.resize(resize)
    .trigger('resize');
})(jQuery);

Upvotes: 0

SimpleUser
SimpleUser

Reputation: 79

Third row btn must be a class $btn = $('.btn');

Upvotes: 1

Related Questions