Skip to content

Instantly share code, notes, and snippets.

@fsk1997
Last active August 20, 2024 13:51
Show Gist options
  • Save fsk1997/012f29061744e0b55a3168ec7c8d5248 to your computer and use it in GitHub Desktop.
Save fsk1997/012f29061744e0b55a3168ec7c8d5248 to your computer and use it in GitHub Desktop.
AstroJS x TailwindCSS Fading Image Component
---
import { Picture } from "astro:assets";
const {
src,
alt = "An image without description",
quality = 40,
size = "base",
className,
imgClassName,
draggable = false,
loadBlur = true,
loading = "lazy",
} = Astro.props;
const sizeLogic = (size) => {
switch (size) {
case "xl":
return 2000;
case "lg":
return 1500;
case "base":
return 1000;
case "sm":
return 500;
case "xs":
return 250;
case undefined:
return 1000;
}
};
---
<Picture
pictureAttributes={{class: className + " block overflow-hidden"}}
densities={[1.5, 2]}
width={sizeLogic(size)}
height={sizeLogic(size)}
class:list={[imgClassName, "w-full h-full object-cover object-center text-neutral-400/0", loadBlur ? "imgLoading" : "imgLoaded"]}
draggable={draggable}
src={src}
loading={loading}
formats={['avif', 'webp']}
alt={alt}
quality={quality}
/>
<style>
.imgLoading{
@apply origin-center bg-neutral-100/[5%] scale-125 brightness-125 md:brightness-50 translate-y-4 blur-md;
}
.imgLoaded{
@apply scale-100 opacity-100 blur-none brightness-100 rotate-0 translate-y-0 transition-all duration-700 ease-in-out;
}
</style>
<script>
let customImage = document.getElementsByClassName("imgLoading");
//loop through the objects of <img/> found on the page with "imgLoading" class, and perform unblurring effect
const unblur = () => {
Object.entries(customImage).forEach((el)=>{
const i = el[1]
if (i.complete) {
i.classList.remove("imgLoading");
i.classList.add("imgLoaded");
// console.log("Image Completed");
} else {
i.addEventListener("load", () => {
i.classList.remove("imgLoading");
i.classList.add("imgLoaded");
// console.log("Image Loaded");
});
i.addEventListener("error", () => {
console.log("error loading image" + i);
// console.log("Image got error");
});
}
})
}
unblur();
document.addEventListener('astro:after-swap', ()=>{
unblur()
})
</script>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment