Multiple image sources in one image element

I’m quite new to Javascript (no jquery pls) and I’m trying to figure out if I can put multiple image sources in one image element

sadImages = document.createElement("img");
sadImages.src = "video/sadness/sadPhoto1.png";
sadImages.className = "projectImages";
sadScrollContainer.append(sadImages);

I would like to add a few more images from the sadness folder (not all!) without creating too many image elements.

I’ve tried writing it like

sadImages.src = "video/sadness/sadPhoto1.png" + "video/sadness/sadPhoto2.png";

and

sadImages.src = "video/sadness/sadPhoto1.png","video/sadness/sadPhoto2.png";

and

sadImages.src = ["video/sadness/sadPhoto1.png","video/sadness/sadPhoto2.png"];

but that doesn’t work. It might be really stupid, but I’m trying to keep my code as short as possible.

28 thoughts on “Multiple image sources in one image element”

  1. RTM perhaps srcset or sizes are useful

    Responsive images has example

    <img srcset="sad-480w.jpg 480w,
             sad-800w.jpg 800w"
     sizes="(max-width: 600px) 480px,
            800px"
     src="sad-800w.jpg"
     alt="sad">
    

    Alternatively use JSON

    console.log(JSON.parse(document.getElementById('img1').dataset.alternative))
    <img id="img1" src="sad1.jpg"  data-alternative='["sad2.jpg","sad3.jpg"]' />
    Reply

Leave a Comment