Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

add remove class in resize window using jQuery

I have this jQuery code for add remove class using jQuery in resize window:

JS:

$(function () {

    $(window).bind("resize", function () {
        console.log($(this).width())
        if ($(this).width() < 500) {
            $('div').removeClass('yellow').addClass('red')
        } else {
            $('div').removeClass('red').addClass('yellow')
        }
    })
})

HTML:

<div style="width:300px; height:100px;" class="yellow"></div>

In action, This worked only when i manualy resize window But in default if device window < 500 this function not work.

how do fix this ?!

Demo HERE

like image 211
Perspolis Avatar asked Dec 19 '22 00:12

Perspolis


2 Answers

Use trigger() to run function on page load

Execute all handlers and behaviors attached to the matched elements for the given event type.

$(window).bind("resize", function () {
    console.log($(this).width())
    if ($(this).width() < 500) {
        $('div').removeClass('yellow').addClass('red')
    } else {
        $('div').removeClass('red').addClass('yellow')
    }
}).trigger('resize');

Demo

You can also use CSS media queries to set the style properties of elements on page load. This will have little performance gain and better user experience than using Javascript.

@media (max-width: 500px) {
    div {
        color: red;
    }
}
@media (min-width: 500px) {
    div {
        color: yellow;
    }
}
like image 65
Tushar Avatar answered Dec 24 '22 01:12

Tushar


Try to invoke the resize event once when the DOM got ready,

$(function(){
   $(window).bind("resize",function(){
    if($(this).width() <500){
      $('div').removeClass('yellow').addClass('red')
    }
    else{
      $('div').removeClass('red').addClass('yellow')
    }
   }).resize();
});

DEMO

like image 40
Rajaprabhu Aravindasamy Avatar answered Dec 24 '22 00:12

Rajaprabhu Aravindasamy