Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Load images based on screen size

I have the following HTML code which displays an image:

<div>
     <img id="wm01" alt="PP" title="PP" u="image" src="theImages/wm01.jpg" />
</div>

What I am trying to do is display a different image depending on the screen size. So first I hide the image with CSS:

#wm01 {
    display: none;
}

And then in my BODY, I add the following code:

var w = window,
d = document,
e = d.documentElement,
g = d.getElementsByTagName('body')[0],
x = w.innerWidth || e.clientWidth || g.clientWidth,
y = w.innerHeight|| e.clientHeight|| g.clientHeight;
if (x<568) {
    //alert(x);
    document.getElementById("wm01").src="theImages/wm01_app.jpg";
    document.getElementById("wm01").style.display = "block";
}
else {
    document.getElementById("wm01").src="theImages/wm01.jpg";
    document.getElementById("wm01").style.display = "block";
}

The image is not showing in any size screen. How can I fix it?

like image 411
SearchForKnowledge Avatar asked May 01 '14 19:05

SearchForKnowledge


2 Answers

No one has suggested using a <picture> element yet.

<picture> has the nice feature that you can specify different images for different window sizes.

For example:

<picture>
    <source srcset="some-bigger.png" media="(min-width: 500px)">
    <img src="some.png" alt="Some picture">
</picture>

For you it would be:

<picture>
    <source srcset="theImages/wm01_app.jpg" media="(min-width: 568px)">
    <img src="theImages/wm01.jpg" alt="PP">
</picture>

Which says, use theImages/wm01_app.jpg whenever the device width is, at minimum, 568px. Otherwise use the default <img> source.

like image 120
zero298 Avatar answered Sep 22 '22 16:09

zero298


Why not use srcset and sizes attributes of the <img>

<img srcset="tiger-320w.jpg 320w,
             tiger-480w.jpg 480w,
             tiger-800w.jpg 800w"
     sizes="(max-width: 320px) 280px,
            (max-width: 480px) 440px,
            800px"
     src="tiger-800w.jpg" alt="Bengal tiger">

For more reference go though Responsive_images

It supported by all major browsers

like image 29
Divyesh Kanzariya Avatar answered Sep 22 '22 16:09

Divyesh Kanzariya