Skip to content

Instantly share code, notes, and snippets.

@djanix
Last active December 13, 2015 21:58
Show Gist options
  • Save djanix/4981016 to your computer and use it in GitHub Desktop.
Save djanix/4981016 to your computer and use it in GitHub Desktop.
mobile -> swap img mobile vs tablet vs desktop
<img src="" data-src-desktop="pathTo/imgName.jpg" data-src-tablet="pathTo/imgName_tablet.jpg" data-src-mobile="pathTo/imgName_tablet.jpg" alt="" />
/* Javascript // jQuery
========================================================================== */
$(function() {
//IE FIX FOR getComputedStyle
if (!window.getComputedStyle) {
window.getComputedStyle = function(el, pseudo) {
this.el = el;
this.getPropertyValue = function(prop) {
var re = /(\-([a-z]){1})/g;
if (prop == 'float') prop = 'styleFloat';
if (re.test(prop)) {
prop = prop.replace(re, function () {
return arguments[2].toUpperCase();
});
}
return el.currentStyle[prop] ? el.currentStyle[prop] : null;
};
return this;
}
}
var device = updateDevice();
swapImages();
$(window).resize(function() {
var newDevice = updateDevice();
if (newDevice != device) {
device = newDevice;
swapImages();
}
});
function swapImages() {
$.each($('img'), function(index, value) {
if ($(this).attr('data-src-' + device)) {
$(this).attr('src', $(this).attr('data-src-' + device));
}
});
}
function updateDevice() {
var device = window.getComputedStyle(document.body,':after').getPropertyValue('content');
//IE8 DEFAULT VALUE
if (!device) { device = 'desktop'; }
//IE9-10 REMOVE QUOTE FROM CONTENT STRING
device = device.replace(/"/g, '');
return device;
}
});
/* CSS // less
========================================================================== */
body:after {
display: none;
}
@media only screen and (max-width: 524px) {
body:after {
content: 'mobile';
}
}
@media only screen and (min-width: 525px) {
body:after {
content: 'tablet';
}
}
@media only screen and (min-width: 960px) {
body:after {
content: 'desktop';
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment