overcaffeinated
overcaffeinated

Reputation: 53

(window.matchMedia().matches) runs code multiple times on resize

I am using if (window.matchMedia().matches to swap some background images on an element depending on the screen resolution. When l resize the page the new (window.matchMedia().matches runs the code within the matchMedia but also continues to run the code from the original resolution.

What am l doing wrong? I have tried changing var names but to no avail.

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();

Upvotes: 0

Views: 163

Answers (0)

Related Questions