I can't get this to do what I want it to do! I'm trying to replace large images with smaller ones for mobile browsers.
Here is the code:
function js_imgs() {
if (document.documentElement.clientWidth <= 600) {
$("img").each(function(){
if ($(this).hasClass('big')) {
var preSrc = $(this).attr('src');
var newSrc = preSrc.substring(preSrc.lastIndexOf('/'), preSrc.lastIndexOf('.'));
$(this).attr('src', newSrc + '-m.' + /[^.]+$/.exec(preSrc));
$(this).removeClass('big').addClass('mobile');
}
});
} else {
$("img").each(function(){
if ($(this).hasClass('mobile')) {
var preSrc = $(this).attr('src');
var newSrc = preSrc.substring(preSrc.lastIndexOf('/'), preSrc.lastIndexOf('.'));
$(this).attr('src', newSrc + '.' + /[^.]+$/.exec(preSrc));
$(this).removeClass('mobile').addClass('big');
}
});
}
};
For the first image, this code works swimmingly. Unfortunately, all the other images have their SRCs rewritten as the first image's SRC. They all turn into the same image; which resize wonderfully, but aren't the right image.
What have I done wrong? I've tried almost all of the variations on this in this thread with no success.