M
M
Maxim2020-02-25 13:15:09
JavaScript
Maxim, 2020-02-25 13:15:09

How to change source srcset on button click?

There is an image on the site inserted like this:

<picture>
  <source srcset="img/cat-before-desktop.png" media="(min-width: 1440px)">
  <source srcset="img/cat-before-table.png" media="(min-width: 768px)">
  <img class="example__before" src="img/cat-before-mobile.png" alt="Толстый кот">
</picture>

With this code, I implement the ability to insert a specific image depending on the resolution of the device.
There are two buttons for this image, "before" and "after".
Added a click event handler to these buttons in JS. Depending on the button pressed, the img src address of the required image changes. But this only works when using img (mobile version). If you open the site on a computer, the source image is naturally used and the JS code no longer works on button clicks, since the change occurs img src, but source is used. How to implement image switching based on images from source?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
S
Sergey Kupletsky, 2020-02-25
@mironov_m

Change when clicking on the button not only the value of img.src, but also source.srcset.
https://developer.mozilla.org/en/docs/Web/API/Elem...

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question