Navigation Menu

Skip to content

Instantly share code, notes, and snippets.

@vcarl
Created September 4, 2015 00:31
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save vcarl/5f3d13e7a14b5a150cb0 to your computer and use it in GitHub Desktop.
Save vcarl/5f3d13e7a14b5a150cb0 to your computer and use it in GitHub Desktop.
// Responsive image handlers.
// By putting `data-filename` and `data-root` attributes on an `img`,
// different image sizes are pulled in automatically.
// e.g. <img data-filename='hero.jpg' data-root='/images/' />
// with media queries to set body:after's `content` to one of mobile, tablet, or desktop
// the `src` will be set to 'hero.mobile.jpg', 'hero.tablet.jpg', or hero.desktop.jpg'
$(function() {
var getSize = function() {
return window
.getComputedStyle(document.body,':after')
.getPropertyValue('content')
.slice(1, -1);
}
var didSizeChange = function(callback) {
var lastSize = getSize();
return function() {
var newSize = getSize();
if (newSize !== lastSize) {
lastSize = newSize;
callback(lastSize);
}
}
}
var getImageSrc = function(size, base, filename) {
// change `filename.ext` to `base/filename.size.ext`
filename = filename.split('.');
filename.splice(1,0,size);
filename = filename.join('.');
return base + filename;
}
updateImageSrcs = function(size) {
$('img').filter(function(i, e){
// filter out any <img> tags without the right attributes
return e.getAttribute('data-filename');
}).each(function(i, e) {
var base, name;
base = e.getAttribute('data-root');
name = e.getAttribute('data-filename');
// if either is missing, throw.
if (base == null || name == null) {throw new Error('Missing attribute on img')}
e.setAttribute('src', getImageSrc(size, base, name));
})
}
$(window).on('resize', didSizeChange(updateImageSrcs));
updateImageSrcs(getSize());
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment