I am using if (window.matchMedia().matches to swap some background images on an element(class) depending on the screen resolution. When l resize the page the corresponding code of the new matchMedia runs but also the code of the previous match media runs as well.
Here is an example of the code:
When the page first loads the correct size of background images gets loaded, when the page is resized both the 4K and 2.5K images are loaded to the div and the speed of the delay halves. For example instead of swapping an image every 5000ms the images get swapped every 2500ms or so. In addition it loads both arrays of images (4k+2.5K) to the class. Anyone can shed some light?
Here is an example of the code:
Code:
var bar_restaurant_images = function () {
// IMAGES 4K
if (window.matchMedia("(max-width: 7680px) and (min-width: 3441px) and (-webkit-max-device-pixel-ratio:1.0)").matches) {
var imagesOfficers = ["officers-mess-section-4k.webp", "officers-mess-section-2-4k.webp", "officers-mess-section-3-4k.webp"];
jQuery(function () {
var i = 0;
jQuery(".officers_mess_section_content_img_wrap").css("background-image", "url(https://officers-mess.co.uk/stage/wp-content/themes/vintclub-child/img/" + imagesOfficers[i] + ")");
setInterval(function () {
i++;
if (i == imagesOfficers.length) {
i = 0;
}
jQuery(".officers_mess_section_content_img_wrap").fadeOut("slow", function () {
jQuery(this).css("background-image", "url(https://officers-mess.co.uk/stage/wp-content/themes/vintclub-child/img/" + imagesOfficers[i] + ")");
jQuery(this).fadeIn("slow");
});
}, 10000);
});
}
else if (window.matchMedia("(max-width: 2560px) and (min-width: 1921px) and (-webkit-max-device-pixel-ratio:1.0)").matches) {
var imagesOfficers2560 = ["officers-mess-section-2560.webp", "officers-mess-section-2-2560.webp", "officers-mess-section-3-2560.webp"];
jQuery(function () {
var i2560 = 0;
jQuery(".officers_mess_section_content_img_wrap").css("background-image", "url(https://officers-mess.co.uk/stage/wp-content/themes/vintclub-child/img/" + imagesOfficers2560[i2560] + ")");
setInterval(function () {
i2560++;
if (i2560 == imagesOfficers2560.length) {
i2560 = 0;
}
jQuery(".officers_mess_section_content_img_wrap").fadeOut("slow", function () {
jQuery(this).css("background-image", "url(https://officers-mess.co.uk/stage/wp-content/themes/vintclub-child/img/" + imagesOfficers2560[i2560] + ")");
jQuery(this).fadeIn("slow");
});
}, 10000);
});
}
};
jQuery(window).on('resize', bar_restaurant_images);
bar_restaurant_images();