Home > Net >  i want 1 image in small screen in 480px then 2 image 580px then 3 image 768px then 4 image 980px
i want 1 image in small screen in 480px then 2 image 580px then 3 image 768px then 4 image 980px

Time:12-15

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:

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.

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.

Example:

console.log([780, 580, 480].filter(el => el > 800).length   1);
console.log([780, 580, 480].filter(el => el > 700).length   1);
console.log([780, 580, 480].filter(el => el > 500).length   1);
console.log([780, 580, 480].filter(el => el > 400).length   1);

  • Related