C
C
corona-net2020-05-15 11:46:15
JavaScript
corona-net, 2020-05-15 11:46:15

Why does the script stop working for dynamic content?

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.

PS If you refresh the page, you will see your uploaded images (i.e. is this already static content?), but they will also pass their address to the text field when clicked and DO NOT pass images as backgrounds.

<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)
R
Rsa97, 2020-05-15
@Rsa97

If there is dynamics, then it is better to hang the event handler on the static parent element of all dynamic elements and use the bubbling.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question