C
C
corona-net2020-05-14 19:07:56
JavaScript
corona-net, 2020-05-14 19:07:56

Why does the script stop working?

There is a site u0763918test1.isp.regruhosting.ru
It displays a list of pictures, when you click on each, the address of the picture is displayed and it is also in a larger form in the container.
It is also possible to upload your own image separately. But here the script stops working, it transmits the address of the image, but stops displaying the image.

Here is the script itself:

<script>
    function countRabbits() {
        let pictures = document.querySelectorAll(".picture");
        let boxTwo = document.querySelector(".box2");
        let boxText = document.querySelector(".boxText99");

        pictures.forEach((picture) => {

            let background = picture.getAttribute("src");

            picture.addEventListener("click", (e) => {
                boxTwo.style.background = `url(${background}) no-repeat center/cover`;
                boxText.innerText = background;
            });

        });
    }

</script>

Answer the question

In order to leave comments, you need to log in

1 answer(s)
O
onzabr, 2020-05-14
@onzabr

This is because you are adding elements dynamically. Try putting a handler on document, then add a check for the element's class.

document.addEventListener('click', event => {
  let picture = event.target;
  let boxTwo = document.querySelector(".box2");
  let boxText = document.querySelector(".boxText99");
  
  if (picture.classList.contains('picture')) { // проверяем, действительно ли это элемент с классом picture
    let background = picture.getAttribute("src");
    boxTwo.style.background = `url(${background}) no-repeat center/cover`;
    boxText.innerText = background;
  }
});

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question