Skip to content

Instantly share code, notes, and snippets.

@lojjic
Created April 7, 2012 04:24
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 lojjic/2325017 to your computer and use it in GitHub Desktop.
Save lojjic/2325017 to your computer and use it in GitHub Desktop.
Zepto plugin for conditionally setting the src of images based on CSS media queries.
/**
* Utility for conditionally setting the src of images based on CSS media queries.
* Example usage:
*
* HTML:
*
* <img class="dynamic" data-src-1="one.png" data-src-2="two.png">
*
* JS:
*
* $('img.dynamic').mediaQuerySrc({
* '(min-width:800px)': 'data-src-1',
* '(min-width:320px)': 'data-src-2'
* });
*
* The argument to mediaQuerySrc is a mapping of media query to the attribute to
* use as the image's src when that media query matches. For instance, in the
* example above, when the viewport width is above 800px the image's src will
* be set to "one.png".
*
* The queries will not respond automatically to changes after page load, e.g.
* resizing of the browser window; if you wish them to respond you'll need to
* manually call mediaQuerySrc again.
*/
(function($) {
var queryCache = {};
function testQuery(query) {
if (!(query in queryCache)) {
var styleEl = $('<style>@media ' + query + ' {html{cursor:wait}}</style>').appendTo($('head')),
isMatch = $('html').css('cursor') === 'wait';
styleEl.remove();
queryCache[query] = isMatch;
}
return queryCache[query];
}
$.fn.mediaQuerySrc = function(queries) {
$(this).each(function() {
var q, attr;
for (q in queries) {
if (queries.hasOwnProperty(q) && testQuery(q) && (attr = this.getAttribute(queries[q]))) {
this.src = attr;
break;
}
}
});
return this;
};
})(Zepto);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment