Pedro Mauricio
Pedro Mauricio

Reputation: 41

.addClass from JQuery not working

I got this piece of code which is working perfectly fine:

$(window).resize(function() {
    if ($(window).width() >= 1024) {
        $("tbody button").addClass( "btn-lg" );
        $("tbody button").removeClass( "btn-sm" );
    } else if ($(window).width() <= 768) {
        $("tbody button").removeClass( "btn-lg" );
        $("tbody button").addClass( "btn-sm" );
    } else {
        $("tbody button").removeClass( "btn-lg" );
        $("tbody button").removeClass( "btn-sm" );
    }
});

But that doesn't work when I open the document since I'm not doing any resize, so I added this:

$(document).ready(function() {
    if ($(window).width() >= 1024) 
        $("tbody button").addClass( "btn-lg" );
    else if ($(window).width() <= 768)
        $("tbody button").addClass( "btn-sm" );
});

But somehow it's not working, I inserted a console.log to see if the code was reaching inside the if and indeed it was, but somehow it's not adding the class.

Any suggestions?

Upvotes: 1

Views: 62

Answers (1)

DLeh
DLeh

Reputation: 24405

One possible alternative would be to wrap the buttons in visible-lg divs instead of using javascript. Example:

<div class="visible-lg">
    <button class="btn btn-lg"></button>
</div>
<div class="visible-md">
    <button class="btn"></button>
</div>
<div class="visible-sm">
    <button class="btn btn-sm"></button>
</div>

Upvotes: 1

Related Questions