Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save willthemoor/0e076c64f2adab3ebc7a to your computer and use it in GitHub Desktop.
Save willthemoor/0e076c64f2adab3ebc7a to your computer and use it in GitHub Desktop.
Convert inline css background images to their @2x counterparts
/*
* retinafyInlineBackgroundImages
* Convert inline css background images to their @2x counterparts
* http://ecotrust.org
* https://gist.github.com/willthemoor/f25e945f716399bd6eec
*
* Made by Will Moore @ Ecotrust
* Under MIT License
*
* NOTE: For background images in your CSS, just use media queries.
* This is specifically for situations where the background images
* are programmitcally inserted as inline CSS on the server side.
*
* Usage: This is a dumb swapper. It expects you to have a second
* version of the image with the same name and @2x appended to it.
* It also does not check to see if your visitor is using a retina
* display. Check first.
*
* if (my_retina_check) {
* $('.element-with-inline-css-background-image).retinafyInlineBackgroundImages();
* }
*
*/
(function( $ ) {
$.fn.retinafyInlineBackgroundImages = function() {
return this.each(function() {
var bg = $(this).css('background-image'),
newbg;
// get rid of the url( and ) wrappings
bg = bg.slice(4, -1)
// IE and Firefox ~39 add quotes around the url
bg = bg.replace(/"/g, "");
// just in case
bg.trim();
// rip off the .jpg and replace it with @2x.jpg
newbg = bg.slice(0, -4) + '@2x.jpg';
// wrap it back up
newbg = 'url('+newbg+')';
$(this).css('background-image', newbg);
});
};
}( jQuery ));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment