Last active
May 15, 2018 00:16
-
-
Save kirkonrails/73fffc83943ad52b6fc0 to your computer and use it in GitHub Desktop.
isRetina javascript function to swap images to @2x
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// To make images retina, add a class "2x" to the img element | |
// and add a <image-name>@2x.png image. Assumes jquery is loaded. | |
function isRetina() { | |
var mediaQuery = "(-webkit-min-device-pixel-ratio: 1.5),\ | |
(min--moz-device-pixel-ratio: 1.5),\ | |
(-o-min-device-pixel-ratio: 3/2),\ | |
(min-resolution: 1.5dppx)"; | |
if (window.devicePixelRatio > 1) | |
return true; | |
if (window.matchMedia && window.matchMedia(mediaQuery).matches) | |
return true; | |
return false; | |
}; | |
function retina() { | |
if (!isRetina()) | |
return; | |
$("img.2x").map(function(i, image) { | |
var path = $(image).attr("src"); | |
path = path.replace(".png", "@2x.png"); | |
path = path.replace(".jpg", "@2x.jpg"); | |
$(image).attr("src", path); | |
}); | |
}; | |
$(document).ready(retina); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment