Search code examples
javascriptbackgroundresolution

Javascript changing background based on user resolution - code fix?


I've been trying to change the background of a school project by finding out what screen resolution the user has, this is my code:

var width = window.innerWidth;
var height = window.innerHeight;

 function getResolution(){
    if (width <= 800 && height <= 600) {
      document.body.style.backgroundImage ="url(Images/ResBackgrounds/800x600.jpg)";
    }
    if (width <= 1024 && height <= 768) {
      document.body.style.backgroundImage ="url(Images/ResBackgrounds/1024x768.jpg)";
    }
    if (width <= 1152 && height <= 864) {
      document.body.style.backgroundImage ="url(Images/ResBackgrounds/1152x864.jpg)";
    } 
    if (width <= 1280 && height <= 720) {
      document.body.style.backgroundImage ="url(Images/ResBackgrounds/1280x720.jpg)";
    } 
    if (width <= 1280 && height <= 768) {
      document.body.style.backgroundImage ="url(Images/ResBackgrounds/1280x768.jpg)";
    }
    if (width <= 1280 && height <= 800) {
      document.body.style.backgroundImage ="url(Images/ResBackgrounds/1280x800.jpg)";
    }
    if (width <= 1280 && height <= 960) {
      document.body.style.backgroundImage ="url(Images/ResBackgrounds/1280x960.jpg)";
    }
    if (width <= 1280 && height <= 1024) {
      document.body.style.backgroundImage ="url(Images/ResBackgrounds/1280x1024.jpg)";
    }
    if (width <= 1360 && height <= 768) {
      document.body.style.backgroundImage ="url(Images/ResBackgrounds/1360x768.jpg)";
    } 
    if (width <= 1366 && height <= 768) {
      document.body.style.backgroundImage ="url(Images/ResBackgrounds/1366x768.jpg)";
    } 
    if (width <= 1440 && height <= 900) {
      document.body.style.backgroundImage ="url(Images/ResBackgrounds/1440x900.jpg)";
    }
    if (width <= 1600 && height <= 900) {
      document.body.style.backgroundImage ="url(Images/ResBackgrounds/1600x900.jpg)";
    }
    if (width <= 1680 && height <= 1050) {
      document.body.style.backgroundImage ="url(Images/ResBackgrounds/1680x1050.jpg)";
    } 
    if (width <= 1920 && height <= 1080) {
      document.body.style.backgroundImage ="url(Images/ResBackgrounds/bkg.jpg)";
    }
 }

For some reason it always jumps to the last if structure, the 1920x1080 one, on any resolution.

I think it's the basic structure of how I did it, maybe it should be if else {}, it does work for 1920x1080p though.


Solution

  • You really should use CSS media queries for this.

    @media screen and (max-width: 800px) , screen and (max-height: 600px) {
        background-image:url("Images/ResBackgrounds/800x600.jpg");
    }
    

    etc

    Your if statements are ALL triggering, so since almost every screen resolution is under 1920x1080, the final statement will trigger every time.