Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to detect window size and then do something with jquery switch statement

i would like to check for the window size with jquery and based on the different resolutions i would like to change the background image. So i was thinking to somehow use the "switch" statement for more cases, but i just don't know how this would look like. This is the basic structure i want but with more options:

if ((screen.width>=1024) && (screen.height>=768)) {
 //do something
}
else {
//do something else
}

Thanks for your help.

like image 748
Mr. Sam Avatar asked Sep 05 '11 10:09

Mr. Sam


People also ask

How can check window width using jquery?

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

Which object is used to retrieve information about window size and height in JavaScript?

window. screen is a JavaScript built-in object type used to retrieve the information about the current browser window. It comprises information related to the screen dimensions such as its width, height, color depth, pixel depth, available width, and available height.

How do I check my screen size in HTML?

Use window. innerWidth and window. innerHeight to get the current screen size of a page.


2 Answers

You should use:

$(window).width();   // returns width of browser viewport
$(document).width(); // returns width of HTML document

$(window).height();   // returns heightof browser viewport
$(document).height(); // returns height of HTML document

and then you could do:

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

if ((width >= 1024  ) && (height>=768)) {
 //do something
}
else {
//do something else
}

EDIT - i don't think that using a switch statement is useful in this case. The switch statement is just an alternate way for the if...else notation that in this case i find more useful because you have multiple comparison to do:

if ((width >= 1280) && (height>=1024)) {
 //do something
}
else if ((width >= 1024  ) && (height>=768)){
//do something else
} else if ((width >= 800) && (height>=600)){
//do something else
}else{
//do something else
}
like image 123
Nicola Peluchetti Avatar answered Sep 24 '22 20:09

Nicola Peluchetti


The switch statement won't let you do stuff like checking for numbers between certain values, and it won't let you check on multiple variables, either...

So for this particular scenario, I think the best fit is actually just a list of if-elseif statements, like you're already on your way to do.

To do "range checks" in switch is really verbose:

switch(windowWidth) {
    case 1:
    case 2:
    case 3:
    case 4:
    case 5:
        //Do something if value is less than or equal to 5
        break;
    case 6:
    case 7:
    case 8:
    case 9:
    case 10:
        //Do something if value is higher than 5 AND less than or equal to 10
        break;
    ...
    ...
}
like image 36
peirix Avatar answered Sep 23 '22 20:09

peirix