4

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

2
  • Initial painting is a different Event then resize. You could extract the logic into a function and bind it to resize as well as document.ready. Commented Sep 1, 2015 at 6:49
  • Check my answer and fiddle in the below. It is the simplest way of doing that Commented Sep 1, 2015 at 6:52

3 Answers 3

7

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;
    }
}
Sign up to request clarification or add additional context in comments.

2 Comments

Using media queries is a good option, but what if OP want to perform some other stuffs when window size is something? OP didn't ask for that but any how just wondering.
@RajaprabhuAravindasamy Yes, that's why I've added both the approach, using Javascript and CSS
4

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

Comments

0

Use media Query

Use the following Css

.yellow{
background:yellow;
}

@media (max-width:500px) {
    .yellow {
    background:red;
    }
}

Check the folowing fiddle

http://jsfiddle.net/adxg3079/

Let me know if it is helpful

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.