Change class when resizing screen

5

I want to change classes as the screen is resized, the code I'm using only works if I refresh the page, I would like to make the class change without needing to refresh the page.

Code:

$(".call-principal").each(function(){
    var scre = $("body").width();
    if ( scre >= 1200 ) {
        $(".icon").addClass("icon-lg");
    } if ( scre > 992 && scre < 1200 ) {
        $(".icon").addClass("icon-md");
    } if ( scre > 768 && scre < 992 ) {
        $(".icon").addClass("icon-sm");
    }  if ( scre < 768 ) {
        $(".icon").addClass("icon-xs");
    }
});
    
asked by anonymous 01.04.2014 / 10:34

1 answer

6

You can use the jQuery resize event. The code below adds the classes when the page loads, and later, every time the screen is resized (firing the resize event):

function addIconClasses() {
    $(".call-principal").each(function(){
        var scre = $("body").width();
        if ( scre >= 1200 ) {
            $(".icon").addClass("icon-lg");
        } if ( scre > 992 && scre < 1200 ) {
            $(".icon").addClass("icon-md");
        } if ( scre > 768 && scre < 992 ) {
            $(".icon").addClass("icon-sm");
        }  if ( scre < 768 ) {
            $(".icon").addClass("icon-xs");
        }
    });
}

$(document).ready(function () {
    // Adicionar classes ao carregar o documento
    addIconClasses();

    $(window).resize(function() {
        // Adicionar sempre que a tela for redimensionada
        addIconClasses();
    });
});

Just a detail: be sure to also remove classes that have already been added whenever resize execute, using removeClass .

If possible, consider using CSS Media Queries . I think they can be very useful in your case, avoiding the need for all this javascript I showed above. For example:

.icon {
    /* Estilo padrão do ícone */
}

/* largura máxima de 992px */
@media screen and (max-width: 992px) {
    .icon {
        /* Estilo modificado do ícone */
    }
}

This code customizes the CSS of class .icon when the screen has a maximum of 992px. You can add another @media to each width you want to customize.

    
01.04.2014 / 11:08