Home > Back-end >  I'd like to make code that dynamically creates overlayed images in a dynamically created contai
I'd like to make code that dynamically creates overlayed images in a dynamically created contai

Time:10-28

can you tell me how to have the following code make multiple images that are layered over one another? Like if I wanted to sometimes have this code post an image1.png with image2.png overlayed over it, but with other if statements true it would post image1.png with image3.png overlayed over it?

// create the images:
var container = document.getElementById("container");
for (var i=0;i<3;i  ) {
  var img = document.createElement("img");
  img.src="https://via.placeholder.com/350x150";
  img.classList.add("img");
  container.appendChild(img);
}

document.querySelectorAll(".img").forEach(function(img,i) {
  img.id="image--" i; // makes more sense to do that in the creation part too
})

document.getElementById('image--1').src = "https://via.placeholder.com/350x150?text=Image1";
<div id="container"></div>

I tried this code but I couldn't figure out a way to make images that overlay one another, it just posts them one after another.

I want to keep using this code because it always posts directly under the most recently created image, making a column of images on your webpage which is exactly the aesthetic I'm looking for.

CodePudding user response:

you'll just have to target the image with onclick or onm ouseover and set the zindex accordingly. for example: image1.addEventListner('click', ()=>{image1.style.zIndex = '5' image2.style.zIndex = '3' image3.style.zIndex = '1'}

CodePudding user response:

So I fiddled with it a whole lot and found out that I had to give image0 absolute positioning first and then everything would be hunky-dory with changing the styles of the subsequent images so they lay ontop of image0.

I tested it and it worked great. Batfreakseyes goes right ontop of batfreak.

  • Related