Search code examples
jqueryimagepathwindowwidth

How to change an image path based on screen width?


I'm trying to change the folder that my images are read from depending on the window width.

I have two folders that contain the different image sizes and I'm wondering if anyone could give me any advice on how to change the path depending on the screens width.

If the screen is regular the <img> would look like

<img src="images/620x410/image1.jpg" alt="">

and If the screen was in the tablet width it would load

<img src="images/310x205/images1.jpg" alt="">

310X205

image1.jpg
image2.jpg

620X410

image1.jpg
image2.jpg

Solution

  • You can use $(window).width(); to determine the size of the window, then set the src of the images accordingly:

    $(function() {
      if($(window).width() <= 310) {
        $("img").each(function() {
          $(this).attr("src", $(this).attr("src").replace("images/620x410/", "images/310x205/"));
        });
      }
    });
    

    You should also note that if I start my browser window at a size of <= 310px, then resize it to above that, your images will still be the smaller version. You might want to consider using the resize event to combat that if required: http://api.jquery.com/resize/