2

In this example, I'm trying to get my if statement using .css to work both on .ready AND .resize but I don't understand how to combine them.

var windowsize = $(window).width();

$(window).ready(function() {

  windowsize = $(window).width();

  if (windowsize > 440) {

    $('body').css("background-color", "blue");

  }
  else { 

$('body').css("background-color", "red");  

  }

}); 

Any help?

0

2 Answers 2

2
function resizeMe(){
  var windowsize = $(window).width();

  if (windowsize > 440) {
    $('body').css("background-color", "blue");
  } else { 
    $('body').css("background-color", "red");  
  }
}


$(window).ready(resizeMe)
         .resize(resizeMe);

or, thanks to @Palpatim, this way:

$(window).on("ready resize", resizeMe);

and can simplify the function to ( thanks to @bfontaine ):

function resizeMe(){
    $('body').css("background-color", $(window).width() > 440 ? "blue" : "red");
}
Sign up to request clarification or add additional context in comments.

3 Comments

Slightly better than "guest271314"'s answer since you're factoring the handler into a standalone function. Now marry that with a single assignment $(window).on("ready resize", resizeMe); and you'll really be cooking with gas. :)
Why not inlining the condition ? $('body').css("background-color", windowsize > 440 ? "blue" : "red");
i didnt dig too deep into the function logic, @bfontaine =) but it may be done this way of course. or even without variable declaration $('body').css("background-color", $(window).width() > 440 ? "blue" : "red");
0

Try

$(window).on("load resize", function() {    
  var windowsize = $(window).width();    
  if (windowsize > 440) {    
    $('body').css("background-color", "blue");    
  }
  else {     
    $('body').css("background-color", "red");      
  };    
}).resize(); 

jsfiddle http://jsfiddle.net/guest271314/mnk7ovmg/

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.