I have the code below:
I use slick slider for creating a slider with background images instead of using img tag. My slider height is 700px and min-height is 400px. With the jquery code below i want to change the background image depending on the window width, but the problem is that the code changes just the image from the first slider. Any help ? :) Thank you
<div class="hero-slider-wraper">
<div class="hero-slider">
<div class="hero-slider-component">
<div class="hero-slider-image" data-img-mobile="http://website.com/wp-content/uploads/2017/01/home1-small.jpg" data-img-large="http://website.com/wp-content/uploads/2017/01/home1.jpg" ></div>
<div class="hero-slider-image" data-img-mobile="http://website.com/wp-content/uploads/2017/01/home2-small.jpg" data-img-large="http://website.com/wp-content/uploads/2017/01/home2.jpg"></div>
<div class="hero-slider-image" data-img-mobile="http://website.com/wp-content/uploads/2017/01/home3-small.jpg" data-img-large="http://website.com/wp-content/uploads/2017/01/home3.jpg"></div>
</div>
</div>
</div>
function resizeSlick() {
var desktopImage = $('.slick-current').attr("data-img-large");
var mobileImage = $('.slick-current').attr("data-img-mobile");
if($(window).width() < 768)
{
$('.slick-current').css('background-image', 'url("'+ mobileImage +'")');
}
else
{
$('.slick-current').css('background-image', 'url("'+ desktopImage +'")');
}
}
//initialize
resizeSlick();
//call when the page resizes.
$(window).resize(function() {
resizeSlick();
});
You need to run the code for each image and not just the .slick-current
function resizeSlick() {
var windowWidth = $(window).width();
$('.hero-slider-image').each(function() {
var desktopImage = $('.slick-current').attr("data-img-large"),
mobileImage = $('.slick-current').attr("data-img-mobile");
if (windowWidth < 768) {
$(this).css('background-image', 'url("' + mobileImage + '")');
} else {
$(this).css('background-image', 'url("' + desktopImage + '")');
}
});
}
//initialize
resizeSlick();
//call when the page resizes.
$(window).resize(resizeSlick);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.