S
S
sokol11112020-04-29 10:44:28
JavaScript
sokol1111, 2020-04-29 10:44:28

The script works on the second click. Why?

There is a block with a gallery of pictures, there is an empty block. When you click on the image, it becomes the background of the bottom block.
The essence of the problem, when loading the page, the first click on the image is wasted, and only from the second everything works as it should. Why?

<div class="img-container" id="img-container">
<img src="....../upload/14271531.jpg" alt="" class="picture" onclick="countRabbits()">
<img src="....../upload/14271531.jpg" alt="" class="picture" onclick="countRabbits()">
</div>
<div class="box2"></div>


function countRabbits() {
        let pictures = document.querySelectorAll(".picture");
        let boxTwo = document.querySelector(".box2");

        pictures.forEach((picture) => {

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

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

        });
    }


Here is an example: u0763918test1.isp.regruhosting.ru

Answer the question

In order to leave comments, you need to log in

1 answer(s)
L
Lord_Dantes, 2020-04-29
@Lord_Dantes

Put the script in document.ready

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question