0

I am trying to change an image source with javascript. When the window size is max-width: 576px; it should change to another source of image that suits the proportion of mobile devices. The element is an image slider.

What I want to know is how to do it in javascript. I tried it already in the following code, but it does not change. I would be so gratefull if you can help me finding my mistake. Thank you very much.

<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">
            <!--<div class="img1 slider-img mySlides"></div>-->
            <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");

            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.addEventListener(changeImage) ;
    </script>

</body>
</html>

2 Answers 2

2

I would recommend to use srcset property, why to use JS for this, when we have all things ready inbuilt.

here is example you can use.

in HTML

    <img srcset=" examples/images/image-384.jpg 1x, examples/images/image-768.jpg 2x" alt="…">

in CSS

.img {
   background-image: url(examples/images/image-384.jpg); 
}
@media 
  (-webkit-min-device-pixel-ratio: 2), 
  (min-resolution: 192dpi) { 
  .img {
    background-image: url(examples/images/image-768.jpg);
  }
}
Sign up to request clarification or add additional context in comments.

2 Comments

Thank you for your help. I tried it but it did not work. The editor does not recognize the following: [at]media (-webkit-min-device-pixel-ratio: 2), (min-resolution: 192dpi) { }. I tried it with [at]media only screen and (max-width: 576px){.img1{ background-image: url(media/slider1-mobile.png);width: 100%;} But the problem is that just the second picture (slider1-mobile.png --> mobile size) shows up permanently and does not switch as expected. Does the 1x and 2x in html gives the elements a certain hirachy? Or do u have an idea what blocks the first picture (start-img-1.png)?
You can follow the article, it has pretty much depth explanation to it. css-tricks.com/a-guide-to-the-responsive-images-syntax-in-html
0

There's something to be said for doing it a different way (see the other answer), but given that you specifically ask about using javascript, and have provided some code, here's a version of your code that does more or less what you want. I've used console.log to make up for the fact that the images aren't present.

<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">
            <!--<div class="img1 slider-img mySlides"></div>-->
            <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");

            function changeImage(y) {
                // Define y here
                var y = window.matchMedia("(max-width: 576px)")
                if (y.matches) { // If media query matches
                    console.log('matches');
                    sliderimg.src="slider1-mobile.png";
                } else {
                    console.log('doesnt match');
                    sliderimg.src="start-img-1.png";
                }
            }
            
            changeImage();

            // attach the event listener to the window;
            // specify that it should be a resize event.

            window.addEventListener('resize',changeImage) ;
    </script>

</body>
</html>

3 Comments

Thank you Chris for your help. I have tried it and the note in the console (match/doesnt match) works all fine. But I dont understand why my picture urls did not change with it. Just the first picture shows up as before. Its all in the same folder so the pictures should get recognized.
Oh, I've just realised: let sliderimg = document.getElementsByClassName("changeimg"); will return an array, so sliderimg.src="slider1-mobile.png"; won't work. Something like document.getElementsByClassName("changeimg")[0].src="slider1-mobile.png" should work
Thank you so much, that was it. :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.