JQuery Window Width else if statement

I am wondering why my last if argument is never executed. I am trying to do this:

$(document).ready(function() { function checkWidth() { var windowSize = $(window).width(); if (windowSize <= 479) { console.log("screen width is less than 480"); } else if (windowSize = 480 && windowSize <= 719) { console.log("screen width is less than 720 but greater than or equal to 480"); } else if (windowSize = 720 && windowSize <= 959) { console.log("screen width is less than 960 but greater than or equal to 720"); } else if (windowSize >= 960) { console.log("screen width is greater than or equal to 960"); } } // Execute on load checkWidth(); // Bind event listener $(window).resize(checkWidth); });​ 

Everything is registered on the console, except for the latter, if. What am I doing wrong?

Thanks,

UPDATE:

For anyone interested, I highly recommend the enquire.js plugin:

http://wicky.nillia.ms/enquire.js/

The best hand-down approach I have found for recognizing media queries in JS.

+4
source share
3 answers

There is no > = pair in the code, and windowSize is not compared, and a new value is assigned as a result of expressions such as windowSize = 480 . Instead, try using this version:

 $(document).ready(function() { function checkWidth() { var windowSize = $(window).width(); if (windowSize <= 479) { console.log("screen width is less than 480"); } else if (windowSize <= 719) { console.log("screen width is less than 720 but greater than or equal to 480"); } else if (windowSize <= 959) { console.log("screen width is less than 960 but greater than or equal to 720"); } else if (windowSize >= 960) { console.log("screen width is greater than or equal to 960"); } } // Execute on load checkWidth(); // Bind event listener $(window).resize(checkWidth); });​ 
+16
source

You are missing a sign:

 else if (windowSize = 720 

and using the equal sign?

Try this instead:

 $(document).ready(function() { function checkWidth() { var windowSize = $(window).width(); if (windowSize < 480) { console.log("screen width is less than 480"); } else if (windowSize < 720) { console.log("screen width is less than 720 but greater than or equal to 480"); } else if (windowSize < 960) { console.log("screen width is less than 960 but greater than or equal to 720"); } else { console.log("screen width is greater than or equal to 960"); } } // Execute on load checkWidth(); // Bind event listener $(window).resize(checkWidth); });​ 

Fiddle

+2
source

This is because of your else if statements. You check for one equal sign that assigns a value.

 if ( windowSize = 480 && windowSize <= 719 ) 

when should you do

 if ( windowSize == 480 && windowSize <= 719 ) 

or> = if this is the intended logic.

+2
source

All Articles