Jeremy P. Beasley
Jeremy P. Beasley

Reputation: 709

Using two jQuery event methods to perform the same set of functions

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?

Upvotes: 2

Views: 51

Answers (2)

Nik Terentyev
Nik Terentyev

Reputation: 2310

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");
}

Upvotes: 2

guest271314
guest271314

Reputation: 1

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/

Upvotes: 0

Related Questions