I've been using the following code for my responsive image replacements:
//HTML:
<img id="testimage" onLoad="minWidth32('test_image')" src="testimage_small.jpg">
//JavaScript:
var screencheck = window.matchMedia("(min-width: 32em)");
function minWidth32(imageName) {
if (screencheck.matches) {
currentImage = document.images[imageName];
currentImage.src = imageName + "_large.jpg";
}
}
(edit)New streamlined version of JavaScript:
var screencheck = window.matchMedia("(min-width: 32em)");
function minWidth32(imageID) {
if (screencheck.matches) {
document.getElementById(imageID).src = imageID + "_large.jpg";
}
}
I really love the "image ID + text string" method for image changes. It allows a single script (per media query) to run as many images as necessary. Many responsive image scripts/plug-ins/libraries involve so. much. mark-up.
But this particular script only sort-of works:
1.) Originally designed for "onMouseOver" rollover effects, this script requires an event listener. This isn't ideal for a responsive images script since browsers are resized and mobile devices change orientation long after an "onLoad" event is over.
2.) This script can only change a non-empty src attribute (from "test_image_small.jpg" to "test_image_large.jpg" in the above example). This means both images are still loaded, wasting bandwidth and making the layout jump around obnoxiously. I'd prefer to fill an empty src attribute.
So basically what I need - and haven't been able to figure out - is this:
//if (screencheck.matches &&
//item is an image tag &&
//item has empty src attribute &&
//item has non-empty ID attribute) {
//set item src attribute = item ID attribute + a text string
//}