I am attempting to switch the image source using JavaScript. Specifically, when the window size is max-width: 576px;, I want it to change to a different image source that fits the aspect ratio of mobile devices. This element is part of an image slider.
I need help figuring out how to accomplish this in JavaScript. I have already tried the following code, but it's not working as expected. Any assistance in identifying my mistake would be greatly appreciated. Thank you.
<DOCTYPE html>
<html lang="de">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<link rel="stylesheet" type="text/css" href="beispiel.css">
</head>
<body>
<!-- Pictures in slideshow -->
<div id="Slider" class="Slide col-1">
<div class="Slide-ontop">
<image class="changeimg slider-img mySlides" src="start-img-1.png" alt="Lets grow together" />
<image class="slider-img mySlides" src="start-img-1.png" alt="Lets grow together" />
<div class="teaser-box">
<h1 class="serif-heading-1">Let us grow together</h1>
<p class="sans-serif-text2">Wie die xx Ihnen helfen kann.</p>
</div>
</div>
</div>
<div class=" button2">
<button class="w3-button demo sans-serif-caption space-button-left" onclick="currentDiv(1)">01</button>
<button class="w3-button demo sans-serif-caption" onclick="currentDiv(2)">02</button>
</div>
<script type="text/javascript">
var slideIndex = 1;
showDivs(slideIndex);
function showDivs(n) {
var i;
var x = document.getElementsByClassName("mySlides");
var dots = document.getElementsByClassName("demo");
if (n > x.length) {slideIndex = 1}
if (n < 1) {slideIndex = x.length}
for (i = 0; i < x.length; i++) {
x[i].style.display = "none";
}
for (i = 0; i < dots.length; i++) {
dots[i].className = dots[i].className.replace(" w3-red", "");
}
x[slideIndex-1].style.display = "block";
dots[slideIndex-1].className += " w3-red";
}
let sliderimg = document.getElementsByClassName("changeimg")[0];
function changeImage(y) {
if (y.matches) { // If media query matches
sliderimg.src = "slider1-mobile.png";
} else {
sliderimg.src = "start-img-1.png";
}
}
var y = window.matchMedia("(max-width: 576px)");
changeImage(y);
y.addListener(changeImage);
</script>
</body>
</html>