Skip to content

Instantly share code, notes, and snippets.

@oresh
Created November 8, 2016 12:59
Show Gist options
  • Save oresh/434ea1de5f7da9320201f2edacbd31a6 to your computer and use it in GitHub Desktop.
Save oresh/434ea1de5f7da9320201f2edacbd31a6 to your computer and use it in GitHub Desktop.
Responsive images by data attribute
var $responsiveImages = $('img[data-mobile-src]');
if ($responsiveImages.length) {
var imgresizeCatch;
var changeImageSrc = function() {
var desktop = getWindowWidth() > 959;
for (var i = 0, len = $responsiveImages.length; i < len; i++) {
var $img = $responsiveImages.eq(i);
if (desktop) {
if ($img.attr('data-desktop-src') != $img.attr('src')) {
$img.attr('src',$img.attr('data-desktop-src'));
}
} else {
if ($img.attr('data-mobile-src') != $img.attr('src')) {
$img.attr('src',$img.attr('data-mobile-src'));
}
}
};
}
changeImageSrc();
$(window).resize(function () {
clearTimeout(imgresizeCatch);
imgresizeCatch = setTimeout(function () {
changeImageSrc();
}, 300);
});
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment