Search code examples
javascripthtmlbackgroundresolution

Changing the background image according to resolution - javascript only


there's a lot of this question scattered over stackoverflow, but I can't seem to find an answer that specifically suits my situation.

I have made a background in HD 1920x1080 for a school project I'm making, and I'm trying to make it fit for every resolution there is. So what I did was resizing this image for every specific resolution, putting me in an awkward spot to code it, as I cannot use jQuery, I'm not allowed to.

I'm thinking of using the screen.width property, but I'd need a length too as I have multiple backgrounds with the ...x768 resoulution.

Is there anyone who'd be able to tell me how to change my body's background, depending on the user's height and width of the screen?

Thank you very much,
Michiel


Solution

  • You may check the window width and change the background depending on the results.

    var width = window.innerWidth;
    var height = window.innerHeight;
    var body = document.body;
    
    if (width <= 1600 && height <= 1000) {
      body.style.background = "url(path/to/1600x1000.jpg)";
    }
    if (width <= 1400 && height <= 900) {
      body.style.background = "url(path/to/1400x900.jpg)";
    }
    // continue as desired
    

    http://jsbin.com/wosaduho/1/

    Even better, use some media queries to reduce javascript required.

    @media screen and (max-width: 1600px) {
     .element {
       background: url(path/to/1600x1000.jpg);
     }
    }
    @media screen and (max-width: 1400px) {
     .element {
       background: url(path/to/1400x900.jpg);
     }
    }