2

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:

1 Answer 1

2

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";
}
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you so much! Works a treat

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.