I've been trying to have a certain image tag behave responsively, by retrieving the most appropriate src
depending on context.
The tag looks like this:
<img
id="picimg"
src="image.jpg"
srcset="image-300x281.jpg 300w,
image-1024x961.jpg 1024w,
image.jpg 1664w"
sizes="(max-width: 499px) 92vw,
(min-width: 500px) 86vw,
(min-width: 960px) 96vw, 96vw"
>
I have even tried this code snippet (found at : http://blog.cloudfour.com/responsive-images-101-part-2-img-required/) to check which src
is in effect each time.
(function() {
var currentSrc, oldSrc, imgEl;
var showPicSrc = function() {
oldSrc = currentSrc;
imgEl = document.getElementById('picimg');
currentSrc = imgEl.currentSrc || imgEl.src;
if (typeof oldSrc === 'undefined' || oldSrc !== currentSrc) {
document.getElementById('logger').innerHTML = currentSrc;
}
};
// You may wish to debounce resize if you have performance concerns
window.addEventListener('resize', showPicSrc);
window.addEventListener('load', showPicSrc);
})(window);
However, the src
seems to never change (it seems to always be image.jpg
), regardless of the browser and its width.
I suspect that, by repeating the same default src
as the last item in the srcset
attribute, it may be affecting the outcome. Or else, maybe the determinant factor is the default size (last item in sizes
).
Your help would be much appreciated.