Is there a way to dynamically update an image source using JavaScript based on the device size?

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>

Answer №1

Instead of using JavaScript, I would recommend utilizing the srcset property which comes built-in and eliminates the need for additional scripting.

Here is an example:

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

Answer №2

While there might be merit in exploring alternative approaches (as mentioned in another response), since you're specifically interested in utilizing JavaScript and have shared some code snippets, here's an adapted version based on your requirements. I've included the use of console.log to simulate image output absence.

<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>

<!-- Slideshow with Images -->

    <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">How xx can assist you.</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) {
                // Set y condition
                var y = window.matchMedia("(max-width: 576px)")
                if (y.matches) { // If media query verifies
                    console.log('matches');
                    sliderimg.src="slider1-mobile.png";
                } else {
                    console.log('doesnt match');
                    sliderimg.src="start-img-1.png";
                }
            }
            
            changeImage();

            // Link event listener to the window for resizing purposes.

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

</body>
</html>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Vue js is throwing an error because it is unable to find the "buscador" property or method that is being referenced in the render function

I am currently diving into the world of laravel combined with Vue js. I am working on integrating a search engine using vue js components, and I would greatly appreciate any help you can provide. Thank you in advance. Below is the Vue js component where t ...

Tips for adjusting the horizontal position of a grid item within a map() loop

I am trying to align the text in my Timeline component from Material Ui always towards the center of the timeline. The TimelineContent contains Paper, Typography (for title and description), and an image. Currently, I have multiple TimelineContent element ...

Leveraging node modules in the browser using browserify - Error: fileType is not recognized

I am currently attempting to utilize the file-type npm package directly in my browser. Despite my efforts, I have encountered an error when trying to run the example code: Uncaught ReferenceError: fileType is not defined (Example code can be found here: ...

What is the process of setting up a subelement in a Vue array?

I am currently working on incorporating an array read feature using Vue.js: {{ this.locations[this.record.carton.LocationID - 1].Location }} Although the code functions properly during runtime, it throws an error upon initial loading: app.js:55125 [Vue wa ...

Are there any plugins available that can create a Ken Burns effect using JQuery?

All I need is a straightforward plugin, not one for creating slideshows. In this case, I only have 1 div and 1 image. The goal is to have the image animate within the div, shifting left/right or up/down without any white space visible. The size of the ima ...

Tips for choosing classes with identical names without resorting to incremental IDs

https://i.stack.imgur.com/EVQVF.pngAre there alternative methods to select classes with the same name but in different table rows? Currently, I am using html class="className + id" and then in jquery to select $('.className'+id)... some code. Is ...

pressing a button unrelated to the 'close' button still triggers the close event

I have a notification bar that features a button in the center that links to another website. There is also a 'close' button on the far right. However, whenever I click the center button, it also triggers the close button. I tried moving the #cl ...

Transform a JavaScript object into a different structure

I need help converting a JavaScript object to another format. For example, my input object in JavaScript looks like this: $scope.name_person= [{ "firstName":"Jean","lastName":"Smith" }] The desired output should look like this: $scope.name_perso= ...

Creating dynamic SQL queries for bulk inserting data into Postgres using Vercel

Can anyone help me with creating an SQL bulk insert query using the sql helper from @vercel/postgres? I have a array of objects with different property types (number, string, date) and need to dynamically build the query. Simply creating a string and passi ...

Issue with firing Facebook pixel after router.push() in Next.js

Within this code block is FB pixel tracking code <Script id="some-id" strategy="afterInteractive">some fb pixel code</Script> The issue arises when navigating to a page containing the script using router.push(SOME_ROUTE). T ...

Utilizing JavaScript to modify the language on a website

As a JavaScript and Bootstrap beginner, I have successfully added the navbar to my website, but now I want to implement a feature where users can change the language of the navbar titles (Home, About us, Our Service, Contact us) by clicking a button at the ...

What is the best way to store the input names and values from a webpage into an object using javascript?

My goal is to save the names and values of inputs on a page into an object. Each input name should serve as the key in the object, with its corresponding value being the value of the input. How can I achieve this? I simply need to store the input names an ...

Concealing the nearest object

I am currently working on using jquery to hide certain content on a website's index page. Within the fiddle, there is commented out code which I have been experimenting with - however, it hides all content divs if any toggle link is clicked. HTML & ...

Having difficulty implementing dynamic contentEditable for inline editing in Angular 2+

Here I am facing an issue. Below is my JSON data: data = [{ 'id':1,'name': 'mr.x', },{ 'id':2,'name': 'mr.y', },{ 'id':3,'name': 'mr.z', },{ & ...

What is the solution to the TypeScript error stating that there is no index signature with a parameter of type 'string' on the 'Object' type?

While working on an Angular project, I came across an issue when writing a Typescript function for a service. The error message stated: "Element implicitly has an 'any' type because expression of type 'string' can't be used to inde ...

Simulating service calls in Jest Tests for StencilJs

When testing my StencilJs application with Jest, I encountered an issue with mocking a service class method used in a component. The service class has only one function that prints text: The Component class: import {sayHello} from './helloworld-servi ...

What's the best way to remove the dead zone on a button with a relative position in HTML and CSS?

Recently, I've come across an issue with styled <a> and <button> tags. This problem arises when using display block or inline-block, some padding, and positioning relative to adjust the position on :active. a { display: inline-block; padd ...

Using Mocha with the --watch flag enabled causes issues with ES6 modules and results in error messages

I've been attempting to configure Mocha to automatically monitor for changes in my files using the --watch flag. I have defined two scripts in package.json as follows: "test": "mocha", "test:watch": "mocha --watch ./test ./game_logic" When I run ...

Necessary elements for communicating with an HTML form on the web

To fully comprehend the question, please take a look at the linked page below. Is there a method to identify the text input field for city/state/zip on the mentioned website? I am in need of allowing users to input city, state or zip into my own text fie ...