{"id":341020,"date":"2021-05-27T07:25:29","date_gmt":"2021-05-27T14:25:29","guid":{"rendered":"https:\/\/css-tricks.com\/?p=341020"},"modified":"2021-05-27T13:30:48","modified_gmt":"2021-05-27T20:30:48","slug":"how-to-show-images-on-click","status":"publish","type":"post","link":"https:\/\/css-tricks.com\/how-to-show-images-on-click\/","title":{"rendered":"How to Show Images on Click"},"content":{"rendered":"\n

Most images on the web are superfluous. If I might be a jerk for a bit, 99% of them aren\u2019t even that helpful at all (although there are rare exceptions<\/a>). That’s because images don\u2019t often complement the text they’re supposed to support and instead hurt<\/em> users, taking forever to load and blowing up data caps like some sort of performance tax.<\/p>\n\n\n\n

Thankfully, this is mostly a design problem today because making images performant and more user-friendly is so much easier than it once was. We have better image formats like WebP<\/a> (and soon, perhaps, JPEG XL<\/a>). We have the magic of responsive images<\/a> of course. And there are tons of great tools out there, like ImageOptim<\/a>, as well as resources such as Addy Osmani\u2019s new book<\/a>. <\/p>\n\n\n\n

Although perhaps my favorite way to improve image performance is with lazy loading<\/a>: <\/p>\n\n\n\n

<img href=\"image.webp\" alt=\"Image description\" loading=\"lazy\"><\/code><\/pre>\n\n\n\n

This image will only load when a user scrolls down the page so it’s visible to the user\u2009\u2014\u2009which removes it from the initial page load and that’s just great! Making that initial load of a webpage lightning fast is a big deal.<\/p>\n\n\n\n

But maybe there are images that should never<\/em> load at all. Perhaps there are situations where it’d be better if a person could opt-into seeing it. Here\u2019s one example: take the text-only version of NPR<\/a> and click around for a bit. Isn\u2019t it… just so great?! It\u2019s readable! There\u2019s no junk all over the place, it respects me as a user and\u2009\u2014\u2009sweet heavens\u2009\u2014\u2009is it fast<\/em>. <\/p>\n\n\n\n

\"\"
Did I just show you an image in a blog post that insults the very concept of images? Yep! Sue me.<\/figcaption><\/figure>\n\n\n\n

So! What if we could show images on a website but only once they are clicked or tapped? Wouldn\u2019t it be neat if we could show a placeholder and swap it out for the real image on click? Something like this:<\/p>\n\n\n\n