Andrew
Andrew

Reputation: 49

How to image swap based on screen size?

I recently started experimenting with bootstrap and scaling things to size when the screen is shrunk. If I have an image that needs to be at least 300px to be readable but the screen is only 250px wide (just for example) they would have to scroll left and right to see the whole image. On ford.com they actually swap the larger image out for a similar image that is smaller, more fit for the screen. Then as you drag the screen larger, it switches back to the larger image. Im assuming this has to do with some form of JS and screen size dimensions. Any thoughts?

Upvotes: 2

Views: 6265

Answers (2)

Dante
Dante

Reputation: 283

Technically the feature you're describing could be achieved through either css, html or javascript.

In CSS you can use media queries to load your images through the background property,

.image {
    background: url("image.jpg");
}
@media only screen and (max-width: 250px) {
    .image {
        background: url("alternative-image.jpg");
    }
}

or, in case you had both images loaded in the html document, through the display property.

.image {
    display: initial;
}
.alternative-image {
    display: none;
}
@media only screen and (max-width: 250px) {
    .image {
        display: none;
    }
    .alternative-image {
        display: initial;
    }
}

Read more about media queries here.

In HTML you can use the picture and source elements,

<picture>
    <source media="(min-width: 250px)" srcset="image.jpg" />
    <img src="alternative-image.jpg" />
</picture>

or the simpler alternative, the srcset attribute.

<img src="alternative-image.jpg" srcset="image.jpg 250px" />

Read more about it here.

Finally, in JavaScript you can use the window size properties to build a function that loads the right image for each size every time the window is resized.

window.onresize = function () {
    if (window.innerWidth < 250) {
        image.setAttribute("src", "alternative-image.jpg");
    } else {
        image.setAttribute("src", "image.jpg");
    }
}

Read a bit about the window size properties here.

PS. Do NOT directly use these examples, as they are incomplete and unoptimized. Their only purpose is to mock the use of the resources they reference.

Upvotes: 6

Chirag S Modi
Chirag S Modi

Reputation: 419

this can be archive in 2 ways.

  1. there is a class in bootstrap V3 img-responsive if you add this class in image tag then it will auto resize when viewport is smaller then image size. Reference : http://getbootstrap.com/css/#images-responsive

  2. OR you can use srcset attribute of image tag

example: <img src="small.jpg" srcset="medium.jpg 1000w, large.jpg 2000w" alt="yah"> in above example you can set image path in srcset in first parameter and on second is image width. in this Browser auto detect viewport width and based on that it will load image.

Upvotes: 1

Related Questions