Search code examples
javascripthtmlimagewebp

How to change picture srcset property on click using javascript


I am trying to change the srcset property of the picture element on click using javascript. I would like to change the image to another webp based image when someone clicks a button.

I can target the current value using var x = document.getElementById("category-banner").srcset;

which outputs the full path of the image, so i assumed it would simply be a case of using the following to set it:

x.srcset="images/products/product-clamp.webp";

it just appears to do nothing at all, there is no error in the console, and the image doesn't change, nor does the value in the html seem to change. I have also tried using src to no avail.

Here is html

    var x = document.getElementById("category-banner").srcset;
    var myFunction = function() {
        x.srcset="images/products/product-clamp.webp";
}
 <picture>
        <source srcset="images/banners/categories/webp/970mm-Balustrade-Panels.webp" type="image/webp" alt="Polaris Hinges now available" id="category-banner">
        <source srcset="images/banners/categories/webp/970mm-Balustrade-Panels.png" type="image/jpeg" alt="Polaris Hinges now available" class="category-banner">
        <img src="images/banners/categories/webp/970mm-Balustrade-Panels.png" alt="Polaris Hinges now available" class="category-banner">
     </picture>

<button onclick="myFunction()">Change Image</button>

and the js code:


Solution

  • You are assigning srcset vale to x variable, try assigning actual img element:

    var img = document.getElementById("category-banner");
        var myFunction = function() {
            img.srcset="images/products/product-clamp.webp";
    }