Skip to content

Instantly share code, notes, and snippets.

@axelmichel
Created February 1, 2016 10:12
Show Gist options
  • Save axelmichel/8806cb39a4afd35bc6d7 to your computer and use it in GitHub Desktop.
Save axelmichel/8806cb39a4afd35bc6d7 to your computer and use it in GitHub Desktop.
facebook like unblur effect with tiny images onload and src switch after
<img class="blurry" src="super-tinyimage-small.jpg" />
<div class="blurry" style="background-image:url(super-tinyimage-small.jpg);"></div>
/* animation to remove the filter */
@keyframes sharpen {
from {
-webkit-filter: blur(50px);
filter: blur(50px);
}
to {
-webkit-filter: blur(0);
filter: blur(0);
}
}
/* the gaussian filter for the tiny images */
.blurry {
-webkit-filter: blur(50px);
filter: blur(50px);
-moz-transform: translateZ(0);
-ms-transform: translateZ(0);
-webkit-transform: translateZ(0);
transform: translateZ(0);
}
/* class to apply the animation */
.blurry.enhanced {
-moz-animation: sharpen 1s both;
-webkit-animation: sharpen 1s both;
animation: sharpen 1s both;
}
/* for background-images only */
.blurry:not(img) {
background-repeat: no-repeat;
background-size: cover;
background-position: center center;
}
window.onload = function load() {
if (!('addEventListener' in window)) { return; }
var collection = document.querySelectorAll(".blurry"),
enhancedClass = 'enhanced';
// loop over all found blurry image elements...
[].forEach.call(collection, function(elm) {
// define type (image or background)
var type = (elm.tagName.toLowerCase() == 'img') ? 'src' : 'bg',
// getting current image or background src
imgSrc = (type === 'bg') ?
elm.style.backgroundImage.slice(4, -1).replace(/"/g, "") :
elm.src,
// getting the data attribute containing the path
// to the full image or use a name replace as fallback
target = (elm.dataset.url) ?
elm.dataset.url :
imgSrc.replace('-small',''),
// a new image element
img = new Image(),
doLoad = function() {
// if done, return
if (elm.className.indexOf(enhancedClass) != -1) {
return;
}
// sets the image source to the element
if(type === 'bg') {
elm.style.backgroundImage = 'url('+target+')';
} else {
elm.src = target;
}
elm.className += ' ' + enhancedClass;
};
// on load, change src of the element image
img.onload = doLoad;
//trigger the load
img.src = target;
});
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment