Skip to content

Instantly share code, notes, and snippets.

@michealengland
Last active October 17, 2020 11:11
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save michealengland/5ca7d0b4b56b4a377c050ed768bbdf15 to your computer and use it in GitHub Desktop.
Save michealengland/5ca7d0b4b56b4a377c050ed768bbdf15 to your computer and use it in GitHub Desktop.
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