I have a parallax SVG background that moves when you scroll and a logo in the navbar. Both SVG and logo have <img src="">
tag. When I apply JavaScript for the SVG it moves both the SVG image and the logo. What should I do?
const handleScroll = (event) => {
const scrollPosition = event.target.scrollingElement.scrollTop;
console.log("handleScroll");
const images = document.querySelectorAll("img");
console.log("images", images);
images.forEach((element) => {
element.style.transform = `translate(0, ${scrollPosition / 10}px)`;
});
};
window.addEventListener("scroll", handleScroll);
//sidebar
const toggleSidebar = () => document.body.classList.toggle("open");
I want only to move my background SVG only.
2
Answers
The main issue was a typo in the handleScroll function where the const and type keywords were mistakenly combined into typconst. Additionally, there was an extra e here at the end of the code which seems to be a typo.
I’ve corrected these errors and verified that the code should now work as expected.
this is because you used
querySelectorAll
to access your background.querySelectorAll
will return an array includes all tags in your DOM that are mached by name ‘img’ and your event will apply on all of them.if you want to apply an event just on one special element it is better to use
getElementById
.and use anId
attriute on your background image element in your HTML.like this: