JSFiddle - React, Tailwind, and code Playground
HTML
<img class="backgroundImage" onload="imageLoaded(this)"/>
<img class="fadeInImg" src="http://lorempixel.com/50/50/technics" onload="testImageLoaded(this)"/>
CSS
.backgroundImage {
opacity: 0; /* set `opacity` to `0` */
width: 200px;
width: 200px;
content: url('http://lorempixel.com/50/50/technics'); /* set intial image */
animation-name: fadein;
animation-iteration-count: 1;
animation-duration: 2500ms;
animation-fill-mode: both;
}
@keyframes fadein {
to {
opacity: 1; /* fade in image */
}
}
@media (min-width: 0) and (max-width: 450px) {
.backgroundImage {
opacity: 0; /* set `opacity` to `0` */
content: url('http://lorempixel.com/50/50/cats'); /* set image */
}
}
@media (min-width: 451px) and (max-width: 1024px) {
.backgroundImage {
opacity: 0; /* set `opacity` to `0` */
content: url('http://lorempixel.com/50/50/city'); /* set image */
}
}
@media (min-width: 1025px) {
.backgroundImage {
opacity: 0; /* set `opacity` to `0` */
content: url('http://lorempixel.com/50/50/sports'); /* set image */
}
}
@keyframes fadeImageIn {
0% {
opacity: 0;
}
100% {
opacity: 1;
}
}
/*the usual method which does not work with media queries*/
/*because you cannot replace the image src url with media query*/
.fadeInImg {
opacity: 0;
}
.loaded {
opacity: 1;
animation: fadeImageIn 3s;
}
JavaScript
//this does not work on something with generated content url
var imageLoaded = (img) => {
console.log('the responsive image is loaded');
}
//usual method works but is not responsive
var testImageLoaded = (img) => {
console.log('the test image is loaded');
img.className += ' loaded';
}