I want to define 4 screen sizes and 4 variable values. I am trying as below.
if ($(window).width() > 789) {
var cyx = 1;
}
if ($(window).width() < 780) {
cyx = 2;
}
if ($(window).width() < 580) {
cyx = 3;
}
if ($(window).width() < 480) {
cyx = 4;
}
Is it possible to do this a shorter way in Javascript?
Thank you.
CodePudding user response:
var width = $(window).width();
var cyx;
if (width > 781) {
cyx = 4;
} else if (width > 780) {
cyx = 3;
} else if (width > 580) {
cyx = 2;
} else if (width > 480) {
cyx = 1;
}
This is how I would do that type of logic. You could 'shorten' it using ternaries, but it would look messy and confusing.
CodePudding user response:
You can use some math:
const cyx = [780, 580, 480].filter(el => el > $(window).width()).length 1;
That's not exactly what the code in the question does, but it's what I assume you actually want.
CodePudding user response:
Another method I've done in the past is to include a 0 height div on the page. I give it an ID like #breakpoint
. Then I set a z-index for it in the CSS stylesheet. For example:
#breakpoint { height:0; z-index:10; }
@media only screen and (min-width: 768px) {
#breakpoint { z-index:5; }
}
@media only screen and (min-width: 1200px) {
#breakpoint { z-index:1; }
}
Then, you simply have to measure the z-index value.
var bp = parseInt($("#breakpoint").css('z-index'));
switch(bp){
case 10:
console.log("Is mobile");
break;
case 5:
console.log("Is tablet");
break;
case 1:
console.log("Is desktop");
break;
}
This cuts down on measurements of the window width, and you can adjust your breakpoints in the CSS code rather than defining widths in the JavaScript code.