Home > Software engineering >  How to change background images using media query without any page load?
How to change background images using media query without any page load?

Time:11-24

Without any page load, I want to change the background image using JavaScript.

const getbg = (bgimg) => {
  if (body.offsetWidth > 780) {
    body.style.backgroundImage = `url(${bgimg[0]})`;
  }
  else if (body.offsetWidth > 780 && body.offsetWidth > 580) {
    body.style.backgroundImage = `url(${bgimg[1]})`;
  }
  else {
    body.style.backgroundImage = `url(${bgimg[2]})`;
  }
};

My code is not working perfectly.

CodePudding user response:

Why not just use css? like the below. It would still change your bg image without page load.

@media(max-width:650px){
 .your-class{
   backround-image: url('image1.jpg');
  }
}

@media(max-width:768px){
 .your-class{
   backround-image: url('image2.jpg');
  }
}

CodePudding user response:

an advice, use it like upside answer.
don't use any javascript for like this simple css process.

ps : if you work on a js framework, it should have it's own method for this.

/* ================= this is latest way of it. ================= */

background-image: image-set(
    url("small-landscape-750x536.jpg") 750w,
    url("large-landscape-2048x1536.jpg") 20480w);
}

/* ================= this is latest way of it. ================= */

  • Related