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.