Change class when resizing screen

Asked

Viewed 4,759 times

5

I want to change classes as the screen is resized, the code I’m using only works if I refresh the page, I’d like to make the class change without having 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");
    }
});

1 answer

6


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

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 one detail: don’t forget to also remove classes that have already been added whenever the resize run, using the 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 class CSS .icon when the screen has at most 992px. You can add one more @media for each width you want to customize.

  • Thank you very much, solved my problem, hugs.

  • Good, I’m glad I helped. If possible, can you mark this answer as the correct one? Hugs!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.