Background Image for Parallax Effect Moves Sideways When Scrolling Up

I’m implementing a parallax effect on my website where the background image changes based on the scroll position. The background image is supposed to stay fixed horizontally and change only vertically as the user scrolls. However, I’m encountering an issue where the background image moves sideways (horizontally) when I scroll up.

Here’s a summary of my setup:

I’m using React and CSS to manage the background image.
The background image changes based on the scroll position.
The image should stay fixed horizontally and only change vertically.
Here’s the relevant code:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>import React, { useEffect, useState } from 'react';
import '../index.css';
const Layout = ({ children }) => {
const [bgImage, setBgImage] = useState("url('Dobra1.webp')");
const [prevBgImage, setPrevBgImage] = useState("");
const [fade, setFade] = useState(false);
const [loading, setLoading] = useState(true);
useEffect(() => {
const images = ["Dobra1.webp", "Dobra2.webp", "Dobra3.webp"];
let loadedImagesCount = 0;
const handleImageLoad = () => {
loadedImagesCount += 1;
if (loadedImagesCount === images.length) {
setLoading(false);
}
};
images.forEach(src => {
const img = new Image();
img.src = src;
img.onload = handleImageLoad;
});
}, []);
useEffect(() => {
const handleScroll = () => {
const scrollPosition = window.scrollY;
if (scrollPosition < window.innerHeight * 2.25) {
setBgImage("url('Dobra1.webp')");
} else if (scrollPosition < window.innerHeight * 5) {
setBgImage("url('Dobra2.webp')");
} else {
setBgImage("url('Dobra3.webp')");
}
};
window.addEventListener('scroll', handleScroll);
return () => {
window.removeEventListener('scroll', handleScroll);
};
}, []);
useEffect(() => {
if (bgImage !== prevBgImage) {
setFade(true);
setPrevBgImage(bgImage);
const timer = setTimeout(() => setFade(false), 1000); // Tempo da transição
return () => clearTimeout(timer);
}
}, [bgImage, prevBgImage]);
return (
<div>
<style>
{`
.loader {
position: fixed;
top: 0;
left: 0;
width: 100%;
height: 100%;
display: flex;
align-items: center;
justify-content: center;
background-color: rgba(0, 0, 0, 0.75);
color: white;
z-index: 9999;
}
.background-overlay {
position: fixed;
top: 0;
left: 0;
width: 100%;
height: 100%;
background-size: cover;
background-position: center;
background-attachment: fixed;
z-index: -1;
transition: opacity 1s ease-in-out;
opacity: 1;
}
.background-overlay.fade {
opacity: 0;
}
@media (max-width: 768px) {
.background-overlay {
background-size: cover;
background-position: center;
background-attachment: scroll;
}
}
`}
</style>
{loading && (
<div className="loader">
Carregando...
</div>
)}
{!loading && (
<>
<div className={`background-overlay ${fade ? 'fade' : ''}`} style={{ backgroundImage: prevBgImage }}></div>
<div className="background-overlay" style={{ backgroundImage: bgImage }}></div>
{children}
</>
)}
</div>
);
};
export default Layout;
</code>
<code>import React, { useEffect, useState } from 'react'; import '../index.css'; const Layout = ({ children }) => { const [bgImage, setBgImage] = useState("url('Dobra1.webp')"); const [prevBgImage, setPrevBgImage] = useState(""); const [fade, setFade] = useState(false); const [loading, setLoading] = useState(true); useEffect(() => { const images = ["Dobra1.webp", "Dobra2.webp", "Dobra3.webp"]; let loadedImagesCount = 0; const handleImageLoad = () => { loadedImagesCount += 1; if (loadedImagesCount === images.length) { setLoading(false); } }; images.forEach(src => { const img = new Image(); img.src = src; img.onload = handleImageLoad; }); }, []); useEffect(() => { const handleScroll = () => { const scrollPosition = window.scrollY; if (scrollPosition < window.innerHeight * 2.25) { setBgImage("url('Dobra1.webp')"); } else if (scrollPosition < window.innerHeight * 5) { setBgImage("url('Dobra2.webp')"); } else { setBgImage("url('Dobra3.webp')"); } }; window.addEventListener('scroll', handleScroll); return () => { window.removeEventListener('scroll', handleScroll); }; }, []); useEffect(() => { if (bgImage !== prevBgImage) { setFade(true); setPrevBgImage(bgImage); const timer = setTimeout(() => setFade(false), 1000); // Tempo da transição return () => clearTimeout(timer); } }, [bgImage, prevBgImage]); return ( <div> <style> {` .loader { position: fixed; top: 0; left: 0; width: 100%; height: 100%; display: flex; align-items: center; justify-content: center; background-color: rgba(0, 0, 0, 0.75); color: white; z-index: 9999; } .background-overlay { position: fixed; top: 0; left: 0; width: 100%; height: 100%; background-size: cover; background-position: center; background-attachment: fixed; z-index: -1; transition: opacity 1s ease-in-out; opacity: 1; } .background-overlay.fade { opacity: 0; } @media (max-width: 768px) { .background-overlay { background-size: cover; background-position: center; background-attachment: scroll; } } `} </style> {loading && ( <div className="loader"> Carregando... </div> )} {!loading && ( <> <div className={`background-overlay ${fade ? 'fade' : ''}`} style={{ backgroundImage: prevBgImage }}></div> <div className="background-overlay" style={{ backgroundImage: bgImage }}></div> {children} </> )} </div> ); }; export default Layout; </code>
import React, { useEffect, useState } from 'react';
import '../index.css';

const Layout = ({ children }) => {
  const [bgImage, setBgImage] = useState("url('Dobra1.webp')");
  const [prevBgImage, setPrevBgImage] = useState("");
  const [fade, setFade] = useState(false);
  const [loading, setLoading] = useState(true);

  useEffect(() => {
    const images = ["Dobra1.webp", "Dobra2.webp", "Dobra3.webp"];
    let loadedImagesCount = 0;

    const handleImageLoad = () => {
      loadedImagesCount += 1;
      if (loadedImagesCount === images.length) {
        setLoading(false);
      }
    };

    images.forEach(src => {
      const img = new Image();
      img.src = src;
      img.onload = handleImageLoad;
    });
  }, []);

  useEffect(() => {
    const handleScroll = () => {
      const scrollPosition = window.scrollY;

      if (scrollPosition < window.innerHeight * 2.25) {
        setBgImage("url('Dobra1.webp')");
      } else if (scrollPosition < window.innerHeight * 5) {
        setBgImage("url('Dobra2.webp')");
      } else {
        setBgImage("url('Dobra3.webp')");
      }
    };

    window.addEventListener('scroll', handleScroll);

    return () => {
      window.removeEventListener('scroll', handleScroll);
    };
  }, []);

  useEffect(() => {
    if (bgImage !== prevBgImage) {
      setFade(true);
      setPrevBgImage(bgImage);
      const timer = setTimeout(() => setFade(false), 1000); // Tempo da transição
      return () => clearTimeout(timer);
    }
  }, [bgImage, prevBgImage]);

  return (
    <div>
      <style>
        {`
          .loader {
            position: fixed;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            display: flex;
            align-items: center;
            justify-content: center;
            background-color: rgba(0, 0, 0, 0.75);
            color: white;
            z-index: 9999;
          }

          .background-overlay {
            position: fixed;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            background-size: cover;
            background-position: center;
            background-attachment: fixed;
            z-index: -1;
            transition: opacity 1s ease-in-out;
            opacity: 1;
          }

          .background-overlay.fade {
            opacity: 0;
          }

          @media (max-width: 768px) {
            .background-overlay {
              background-size: cover;
              background-position: center;
              background-attachment: scroll;
            }
          }
        `}
      </style>
      {loading && (
        <div className="loader">
          Carregando...
        </div>
      )}
      {!loading && (
        <>
          <div className={`background-overlay ${fade ? 'fade' : ''}`} style={{ backgroundImage: prevBgImage }}></div>
          <div className="background-overlay" style={{ backgroundImage: bgImage }}></div>
          {children}
        </>
      )}
    </div>
  );
};

export default Layout;

When I scroll up, the background image shifts slightly to the left. I need the image to stay fixed horizontally and only change vertically as I scroll. How can I fix this issue so the background image doesn’t move sideways when scrolling?

Any help would be greatly appreciated!

Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa Dịch vụ tổ chức sự kiện 5 sao Thông tin về chúng tôi Dịch vụ sinh nhật bé trai Dịch vụ sinh nhật bé gái Sự kiện trọn gói Các tiết mục giải trí Dịch vụ bổ trợ Tiệc cưới sang trọng Dịch vụ khai trương Tư vấn tổ chức sự kiện Hình ảnh sự kiện Cập nhật tin tức Liên hệ ngay Thuê chú hề chuyên nghiệp Tiệc tất niên cho công ty Trang trí tiệc cuối năm Tiệc tất niên độc đáo Sinh nhật bé Hải Đăng Sinh nhật đáng yêu bé Khánh Vân Sinh nhật sang trọng Bích Ngân Tiệc sinh nhật bé Thanh Trang Dịch vụ ông già Noel Xiếc thú vui nhộn Biểu diễn xiếc quay đĩa Dịch vụ tổ chức tiệc uy tín Khám phá dịch vụ của chúng tôi Tiệc sinh nhật cho bé trai Trang trí tiệc cho bé gái Gói sự kiện chuyên nghiệp Chương trình giải trí hấp dẫn Dịch vụ hỗ trợ sự kiện Trang trí tiệc cưới đẹp Khởi đầu thành công với khai trương Chuyên gia tư vấn sự kiện Xem ảnh các sự kiện đẹp Tin mới về sự kiện Kết nối với đội ngũ chuyên gia Chú hề vui nhộn cho tiệc sinh nhật Ý tưởng tiệc cuối năm Tất niên độc đáo Trang trí tiệc hiện đại Tổ chức sinh nhật cho Hải Đăng Sinh nhật độc quyền Khánh Vân Phong cách tiệc Bích Ngân Trang trí tiệc bé Thanh Trang Thuê dịch vụ ông già Noel chuyên nghiệp Xem xiếc khỉ đặc sắc Xiếc quay đĩa thú vị
Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa
Thiết kế website Thiết kế website Thiết kế website Cách kháng tài khoản quảng cáo Mua bán Fanpage Facebook Dịch vụ SEO Tổ chức sinh nhật