-1

I have the same image at multiple widths, e.g. balloon-35.webp, balloon-40.webp, balloon-90.webp.

I also have multiple img elements with different widths, e.g. <img width="35"/>, <img width="40"/>, <img width="90"/>.

Can I specify the srcset attribute for each img with the 3 files mentionned above and have the img element chose the right file according to the width attribute? For example, if the width of the img is 35, then the 35 file is chosen.

Or is my only option to change the src attribute with the right file depending on the width? Or is there another way to achieve what I want?

Cheers!

Maxime Dupré
  • 5,319
  • 7
  • 38
  • 72

1 Answers1

0

Here is the snippet code, i have design for you just enter the images URL in the array of images as mention imagesUrls = ['balloon-35.webp', 'balloon-40.webp', 'balloon-90.webp'];. Value of url should be anything just the last 7 character 40.webp etc should be same as you mention in your upper description.

var a = document.getElementsByTagName("a");

function stups(){

  var tagWidth = a[0].getAttribute("width");
  document.getElementById("demo").innerHTML = tagWidth;
  console.log(tagWidth);
var src = "";
var imagesUrls = ['balloon-35.webp', 'balloon-40.webp', 'balloon-90.webp'];

for (var img of imagesUrls)
 {
var width = img.substr(img.length - 7);
var widthValue = width.substring(0, 2);
if (tagWidth.substring(0, 2) === widthValue){
  src = img;
 }
}
console.log(src);
document.getElementById("imageClass").src = src;
}
<BUTTON ONCLICK="stups()">VALUE FINDER </BUTTON>
<a value="this is a value" width="35px" href="value"><img id="imageClass" src=""> values rule!!</a>
<p id="demo"></p>

Do Ping me up, If you think that i did something good for you. Cheers!

Abdul Moeez
  • 1,331
  • 2
  • 13
  • 31