Last active
September 12, 2022 22:23
-
-
Save simboonlong/7e2d6fd86efd7398a9ac19e47caa80ef to your computer and use it in GitHub Desktop.
custom lazy load background image for slick.js
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<html> | |
<head> | |
<link rel="stylesheet" type="text/css" href="//cdn.jsdelivr.net/jquery.slick/1.6.0/slick.css"/> | |
<link rel="stylesheet" type="text/css" href="//cdn.jsdelivr.net/jquery.slick/1.6.0/slick-theme.css"/> | |
<script type="text/javascript" src="https://code.jquery.com/jquery-1.12.0.min.js"></script> | |
<script type="text/javascript" src="//cdn.jsdelivr.net/jquery.slick/1.6.0/slick.min.js"></script> | |
<style> | |
#s { | |
border: solid 1px red; | |
width: 640px; | |
height: 480px; | |
} | |
.mycustomimg { | |
width: 350px; | |
height: 150px; | |
background-repeat: no-repeat; | |
transition: opacity 0.4s 0.5s ease-out; /* delay to be same as slick speed */ | |
opacity: 0; | |
} | |
.mycustomimg.is-lazy-loaded { | |
opacity: 1; | |
background-image: url('http://placehold.it/350x150'); | |
} | |
</style> | |
</head> | |
<body> | |
<div id="s"> | |
<div> | |
<h3>1</h3> | |
</div> | |
<div> | |
<h3>2</h3> | |
<div class="mycustomimg lazy-bg-img"></div> | |
</div> | |
<div> | |
<h3>3</h3> | |
</div> | |
</div> | |
<script> | |
var lazyBgImg = function( el ) { | |
var lazyBgImgs = $(el).find('.lazy-bg-img'); | |
lazyBgImgs.each(function(i) { | |
var el = $(this); | |
if ( !el.hasClass('is-lazy-loaded') ) { | |
el.addClass('is-lazy-loaded'); | |
} | |
}); | |
} | |
var s = $('#s').slick({ | |
speed: 500, | |
}); | |
s.on('beforeChange', function(event, slick, currentSlide, nextSlide) { | |
if ( currentSlide !== nextSlide ) { | |
lazyBgImg( $(slick.$slides.get(nextSlide)) ); | |
} | |
}); | |
</script> | |
</body> | |
</html> | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment