Search code examples
javascriptjquerymobileresponsive-designjquery-backstretch

Serving a different set of images for mobile


I'm using jQuery-backstretch to serve fading background images on my page. This works well for desktop, but because of how detailed these images are, I need to use another set of of images for mobile users only.

So far I found out how to disable the script for mobile (or use different images for individual pages: Using Backstretch for different images for individual pages), but I would love to find out how to serve a totally different set of images just for mobile.

<script>
function detectmob() {
  if(window.innerWidth <= 800 && window.innerHeight <= 600) {
     return true;
   } else {
     return false;
   }
}

if(!detectmob()){

    $.backstretch(["imgs/1.jpg"
, "imgs/2.jpg"
, "imgs/3.jpg"
, "imgs/4.jpg"
], {duration: 1800, fade: 4000});
}
</script>

Does anyone has a solution? Many thanks.


Solution

  • You somehow have to detect the viewport size and invoke backstretch based on that.

    Instead of doing that by checking the window width, you can use matchMedia.

    if (window.matchMedia("(min-width: 992px)").matches) {
     // phone
    $.backstretch(["imgs/1_phone.jpg"
    , "imgs/2_phone.jpg"
    , "imgs/3_phone.jpg"
    , "imgs/4_phone.jpg"
    ], {duration: 1800, fade: 4000});
    
    } else {
    
    //tab or desktop
    $.backstretch(["imgs/1.jpg"
    , "imgs/2.jpg"
    , "imgs/3.jpg"
    , "imgs/4.jpg"
    ], {duration: 1800, fade: 4000});
    
    
    }
    

    You could do something like this.