Answer the question
In order to leave comments, you need to log in
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`;
});
});
}
Answer the question
In order to leave comments, you need to log in
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question