Skip to content

Instantly share code, notes, and snippets.

@michealengland
Last active Oct 17, 2020
Embed
What would you like to do?
Intersection Observer Image Blur
// The element we will observe.
const heroImage = document.querySelector('img');
// Observer options.
const options = {
root: null,
rootMargin: '0px',
threshold: 0.7,
};
// Callback function executed during observe.
const callback = function( entries, observer ) {
// Target the first entry available.
let observedImg = entries[0];
// Log observer entry data.
console.log( observedImg );
// Add or remove the blur.
! observedImg.isIntersecting ? observedImg.target.style.filter = 'blur(10px)' : observedImg.target.style.filter = 'blur(0px)';
};
// Construct Intersection Observer.
const observer = new IntersectionObserver( callback, options );
// Observe if element is present.
if ( heroImage ) {
observer.observe( heroImage );
}
// Callback function executed during observe.
const callback = function( entries, observer ) {
// Target the first entry available.
let observedImg = entries[0];
// Log observer entry data.
console.log( observedImg );
// Add or remove the blur.
! observedImg.isIntersecting ? observedImg.target.style.filter = 'blur(10px)' : observedImg.target.style.filter = 'blur(0px)';
};
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Blur on Scroll</title>
<link rel="stylesheet" href="style.css">
</head>
<body>
<!-- the element we're going to observe.-->
<figure>
<img src="dino-reichmuth-A5rCN8626Ck-unsplash.jpg" alt="Photo by Dino Reichmuth on Unsplash">
</figure>
</body>
<!-- import JS -->
<script src="blur.js" type="text/javascript"></script>
</html>
// Construct Intersection Observer.
const observer = new IntersectionObserver( callback, options );
// Observe if element is present.
if ( heroImage ) {
observer.observe( heroImage );
}
body {
margin: 0;
min-height: 200vh;
padding: 0;
}
figure {
margin: 0 auto;
overflow: hidden;
padding: 0;
position: relative;
}
img {
display: block;
margin: 0 auto;
max-height: 100vh;
transition: 0.4s linear; // adjust speed on blur effect.
width: auto;
}
// The element we will observe.
const heroImage = document.querySelector('img');
// Observer options.
const options = {
root: null,
rootMargin: '0px',
threshold: 0.7,
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment