benjones
benjones

Reputation: 35

click to add image JavaScript

At the moment I am developing a site where when you click, an image is added to the page.

Is it possible for the code to still work but for it too not effect images further down the page?

I've tried to change so it doesn't link to "img" tag but this doesn't seem to work. First time working with JS so very new to it all.

Js looks like this at the moment

const images = [
"benjones_con4.jpg", 
"ben_jones_ts2.jpg", 
"benjones_con3.jpg"
]

let i = 0 

function placeImage(x, y) {

  const nextImage = images[i]

  const img = document.createElement("img")
  img.setAttribute("src", nextImage)
  img.style.left = x + "px"
  img.style.top = y + "px"

  document.body.appendChild(img)

  i = i + 1

  if (i >=images.length) {
    i = 0
  }
}

document.addEventListener("click", function (event) {

  event.preventDefault()
  placeImage(event.pageX, event.pageY)
})

document.addEventListener("touchend", function (event){
  event.preventDefault()
  placeImage(event.pageX, event.pageY)

})
img {
  position: absolute;
  transform: translate(-50%, -50%) scale(0.5);
  animation: fadein 0.5s;
}

@keyframes fadein {
  0% {opacity: 0;}
  100% {opacity: 1;}
}

Upvotes: 2

Views: 136

Answers (1)

Vitaly Yastremsky
Vitaly Yastremsky

Reputation: 386

As I understand from the latest comment, if you don't want that loaded img conflict with other "img" tags on your page, you need add some meaningful class for created img element. And define styles for loaded image separately.

function placeImage(x, y) {
  const nextImage = images[i]
  const img = document.createElement("img")
  // here adding class for created img tag
  img.classList.add('external-loaded-img')
  ...
}
// instead of global img, define for class
.external-loaded-img {
  position: absolute;
  transform: translate(-50%, -50%) scale(0.5);
  animation: fadein 0.5s;
}

@keyframes fadein {
  0% {opacity: 0;}
  100% {opacity: 1;}
}

Upvotes: 1

Related Questions