javascripthtmlcsscss-animationsdom-manipulation

Add opacity and transition to background image and div


As demonstrated by the snippet. I created this story part just for mobile devices and will integrate it into the current website. The issue I'm having is that although it functions OK on its own, when I added it to an existing website (between areas of the page), it didn't function as expected. Therefore, I want it to function as a separate area on the website.

As you can see in the attached photos. I want to add this story section to existing website and apply opacity to both the background image and the div when the div goes up. The background image changes and flickers as well. I want to fix it.

It's a window.onscroll based code and there is lots of other elements in the website so its breaking my code and background image is not showing in within a webiste.

As, I'm new to DOM manipulation and animations. So, i need help to

  function scrollPictureChange() {
        var main = document.querySelector(".main"),
          sections = main.querySelectorAll(".section"),
          BG = main.querySelector(".BG"),
          el = document.querySelector(".show"),
          cords,
          index = 0,
          h = window.innerHeight,
          lastIndex = null,
          offset = 0;

        applyBG(0);
        window.addEventListener("scroll", function () {
          scrollY = Math.abs(document.body.getClientRects()[0].top);
          index = Math.floor(scrollY / (h - offset));

          if (index != lastIndex) {
            // on index change
            if (lastIndex != null) {
              applyBG(index);
            }
            lastIndex = index;
          }

          el.innerText = `index : ${index} height : ${h} top : ${scrollY}`;
        });

        function applyBG(index) {
          BG.classList.remove("anim");
          setTimeout(function () {
            BG.style.backgroundImage = `url(${sections[index + 1].getAttribute(
              "BGurl"
            )})`;
            BG.classList.add("anim");
          }, 300);
        }
      }

      window.onload = scrollPictureChange;
      window.onresize = scrollPictureChange;
   
body {
    margin: 0;
    padding: 0;
    box-sizing: border-box;
    overflow-x: hidden;
}

.section {
    height: 100vh;
    width: 100%;
    display: flex;
    z-index: 1;
    position: relative;
    background-size: 100% 100% !important;
}

.text {
    margin: auto;
}

.text p {
    font-family: 'Lato';
    font-style: normal;
    font-weight: 500;
    font-size: 18px;
    line-height: 149%;
    color: #263244;
}

.text h1 {
    margin-bottom: 20px;
    font-family: 'Lato';
    font-style: normal;
    font-weight: 700;
    font-size: 50px;
    line-height: 0px;
    color: #FFFFFF;
    margin-bottom: 50px;
}

.text .story-detail {
    width: 300px;
    border-radius: 20px;
    background: radial-gradient(76.31% 191.89% at 13.43% 22.19%, rgba(226, 228, 231, 0.8) 0%, rgba(228, 228, 229, 0.368) 100%);
    backdrop-filter: blur(10px);
    padding: 23px;
}

.text .story-description {
    width: 321px;
    border-radius: 20px;
    background: radial-gradient(76.31% 191.89% at 13.43% 22.19%, rgba(226, 228, 231, 0.8) 0%, rgba(228, 228, 229, 0.368) 100%);
    backdrop-filter: blur(10px);
    padding: 23px;

}

.BG {
    position: fixed;
    z-index: 0;
    opacity: 1;
    transition: opacity 10s ease-in-out;
    height: 100%;
}

.anim {
    opacity: 1;
}

.show {
    color: orange;
}
  <div class="main">
      <div class="section BG">
        <div class="show"></div> 
      </div>
      <div
        class="section"
        BGurl="https://i.postimg.cc/9QYL3ytR/mobile-camp.png"
      >
        <div class="text">
          <div style="margin-inline: 20px">
            <h1>Our Story</h1>
            <div class="story-detail">
              <p>
                We saw a gap between what people need and what banks offer. It
                means millions of us aren't getting the banking experience we
                deserve for different reasons.
              </p>
            </div>
          </div>
        </div>
      </div>

      <div
        class="section"
        BGurl="https://i.postimg.cc/9QYL3ytR/mobile-camp.png"
      >
        <div class="text">
          <div style="margin-inline: 20px">
            <div class="story-description">
              <p>
                Traditional banks don’t focus on customers' experience, their
                systems may be slow and outdated, they may prioritize a specific
                group of people, or perhaps they lack the ability to innovate,
                and so on.
              </p>
            </div>
          </div>
        </div>
      </div>

      <div
        class="section"
        BGurl="https://i.postimg.cc/cLPLS8xW/mobile-desert.png"
      >
        <div class="text">
          <div style="margin-inline: 20px">
            <div class="story-description">
              <p>
                So since we're passionate about solving problems and bridging
                gaps, we looked into and identified the challenges and
                capabilities we'll need to build a bank here in the Kingdom.
              </p>
            </div>
          </div>
        </div>
      </div>

      <div
        class="section"
        BGurl="https://i.postimg.cc/mZnqV38T/mobile-birds.png"
      >
        <div class="text">
          <div style="margin-inline: 20px">
            <div class="story-description">
              <p>
                With the best local and international expertise, we began
                building an innovative digital bank designed by and for the
                people. We believe that the most effective way to build a bank
                for people is to do it with them. This is our philosophy. So, we
                started building it with the help of people like you.
              </p>
            </div>
          </div>
        </div>
      </div>
      <div class="section" BGurl="https://i.postimg.cc/k513m0Fb/mountain.png">
        <div class="text">
          <div style="margin-inline: 20px">
            <div class="story-description">
              <p>
                At D360, innovation starts with someone’s passion for improving
                financial services. To that person, we say: Never stop offering
                solutions to your needs. These solutions will not only benefit
                you, but will significantly impact the lives of millions.
              </p>
            </div>
          </div>
        </div>
      </div>
    </div>


Solution

  • It is painful to do what you want with the method you follow. Because of that, I suggest the getBoundingClientRect() method. The method is a Web API which returns information about the size of an element and its position in your page.

    The left, top, right, bottom, x, y, width, and height properties describe the position and size of the overall rectangle in pixels. Properties other than width and height are relative to the top-left of the viewport.

    Source: Further information and examples


    Sample (for your question)

    1. Create 10 Divs (optional)
    <div class="div">
        <p>Sample sentence is here!</p>
    </div>
    
    1. Define style to the Divs with CSS
    .div {
        /* This must be exist. */
        opacity: 0;
    
        /* OPTIONAL STYLE  */
        width: 300px;
        border:1px solid black;
        border-radius: 20px;
        margin:auto;
        padding: 10px;
        background-color: white;
        transition: opacity 1s;
        margin-bottom: 20px;
    }
    
    1. Set your background images' path in an array in JS
    const bgImgs = ['https://picsum.photos/id/237/1920/1080','https://picsum.photos/id/102/1920/1080','https://picsum.photos/id/202/1920/1080','https://picsum.photos/id/99/1920/1080','https://picsum.photos/id/63/1920/1080','https://picsum.photos/id/6/1920/1080','https://picsum.photos/id/10/1920/1080','https://picsum.photos/id/19/1920/1080','https://picsum.photos/id/80/1920/1080','https://picsum.photos/id/111/1920/1080'];
    
    1. Fetch all of your Divs in JS
    const divs = document.querySelectorAll('.div');
    
    1. Get each Div's info, and make 3 rule with IF-Statement in JS
    for (var i = 0; i < divs.length; i++) {
        const div = divs[i];
        const rect = div.getBoundingClientRect();
        if (rect.top >= 0 && rect.bottom <= window.innerHeight) {
            div.style.opacity = 1;
            document.body.style.backgroundImage = `url('${bgImgs[i]}')`;
        } else if (rect.top < 0 && rect.bottom > 0) {
            div.style.opacity = rect.bottom / window.innerHeight;
        } else if (rect.top > 0 && rect.top < window.innerHeight) {
            div.style.opacity = 1 - (rect.top / window.innerHeight);
        }
    }
    

    In the situation, the first condition makes the relevant element's opacity 1 (this means showing us the element), and then change background image. The second condition means the next element, and finally the third condition reduces the previous element's opacity slowly.

    Test the sample

    const bgImgs = ['https://picsum.photos/id/237/1920/1080','https://picsum.photos/id/102/1920/1080','https://picsum.photos/id/202/1920/1080','https://picsum.photos/id/99/1920/1080','https://picsum.photos/id/63/1920/1080','https://picsum.photos/id/6/1920/1080','https://picsum.photos/id/10/1920/1080','https://picsum.photos/id/19/1920/1080','https://picsum.photos/id/80/1920/1080','https://picsum.photos/id/111/1920/1080'];
    function handleScroll(){
        const divs = document.querySelectorAll('.div');
        for (var i = 0; i < divs.length; i++) {
            const div = divs[i];
            const rect = div.getBoundingClientRect();
            if (rect.top >= 0 && rect.bottom <= window.innerHeight) {
                div.style.opacity = 1;
                document.body.style.backgroundImage = `url('${bgImgs[i]}')`;
            } else if (rect.top < 0 && rect.bottom > 0) {
                div.style.opacity = rect.bottom / window.innerHeight;
            } else if (rect.top > 0 && rect.top < window.innerHeight) {
                div.style.opacity = 1 - (rect.top / window.innerHeight);
            }
        }
    };
    window.addEventListener('scroll', handleScroll);
    handleScroll();
    html, body {
        /* OPTIONAL STYLE  */
        margin: 20px 0 20px 0;
        padding: 0;
        transition: background-image 1s;
        
        /* The fixed background image */
        background-repeat: no-repeat;
        background-attachment: fixed;
    }
    .div {
        /* This must be exist. */
        opacity: 0;
    
        /* OPTIONAL STYLE  */
        width: 300px;
        border:1px solid black;
        border-radius: 20px;
        margin:auto;
        padding: 10px;
        background-color: white;
        transition: opacity 1s;
        margin-bottom: 20px;
    }
    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <meta http-equiv="X-UA-Compatible" content="IE=edge">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <title>Opacity Divs</title>
    </head>
    <body>
        <div class="div">
            <p>We saw a gap between what people need and what banks offer. It means millions of us aren't getting the banking experience we deserve for different reasons.</p>
            <p>Traditional banks don’t focus on customers' experience, their systems may be slow and outdated, they may prioritize a specific group of people, or perhaps they lack the ability to innovate, and so on.</p>
            <p>We saw a gap between what people need and what banks offer. It means millions of us aren't getting the banking experience we deserve for different reasons.</p>
            <p>Traditional banks don’t focus on customers' experience, their systems may be slow and outdated, they may prioritize a specific group of people, or perhaps they lack the ability to innovate, and so on.</p>
            <p>We saw a gap between what people need and what banks offer. It means millions of us aren't getting the banking experience we deserve for different reasons.</p>
        </div>
        <div class="div">
            <p>We saw a gap between what people need and what banks offer. It means millions of us aren't getting the banking experience we deserve for different reasons.</p>
            <p>Traditional banks don’t focus on customers' experience, their systems may be slow and outdated, they may prioritize a specific group of people, or perhaps they lack the ability to innovate, and so on.</p>
            <p>We saw a gap between what people need and what banks offer. It means millions of us aren't getting the banking experience we deserve for different reasons.</p>
            <p>Traditional banks don’t focus on customers' experience, their systems may be slow and outdated, they may prioritize a specific group of people, or perhaps they lack the ability to innovate, and so on.</p>
            <p>We saw a gap between what people need and what banks offer. It means millions of us aren't getting the banking experience we deserve for different reasons.</p>
        </div>
        <div class="div">
            <p>We saw a gap between what people need and what banks offer. It means millions of us aren't getting the banking experience we deserve for different reasons.</p>
            <p>Traditional banks don’t focus on customers' experience, their systems may be slow and outdated, they may prioritize a specific group of people, or perhaps they lack the ability to innovate, and so on.</p>
            <p>We saw a gap between what people need and what banks offer. It means millions of us aren't getting the banking experience we deserve for different reasons.</p>
            <p>Traditional banks don’t focus on customers' experience, their systems may be slow and outdated, they may prioritize a specific group of people, or perhaps they lack the ability to innovate, and so on.</p>
            <p>We saw a gap between what people need and what banks offer. It means millions of us aren't getting the banking experience we deserve for different reasons.</p>
        </div>
        <div class="div">
            <p>We saw a gap between what people need and what banks offer. It means millions of us aren't getting the banking experience we deserve for different reasons.</p>
            <p>Traditional banks don’t focus on customers' experience, their systems may be slow and outdated, they may prioritize a specific group of people, or perhaps they lack the ability to innovate, and so on.</p>
            <p>We saw a gap between what people need and what banks offer. It means millions of us aren't getting the banking experience we deserve for different reasons.</p>
            <p>Traditional banks don’t focus on customers' experience, their systems may be slow and outdated, they may prioritize a specific group of people, or perhaps they lack the ability to innovate, and so on.</p>
            <p>We saw a gap between what people need and what banks offer. It means millions of us aren't getting the banking experience we deserve for different reasons.</p>
        </div>
        <div class="div">
            <p>We saw a gap between what people need and what banks offer. It means millions of us aren't getting the banking experience we deserve for different reasons.</p>
            <p>Traditional banks don’t focus on customers' experience, their systems may be slow and outdated, they may prioritize a specific group of people, or perhaps they lack the ability to innovate, and so on.</p>
            <p>We saw a gap between what people need and what banks offer. It means millions of us aren't getting the banking experience we deserve for different reasons.</p>
            <p>Traditional banks don’t focus on customers' experience, their systems may be slow and outdated, they may prioritize a specific group of people, or perhaps they lack the ability to innovate, and so on.</p>
            <p>We saw a gap between what people need and what banks offer. It means millions of us aren't getting the banking experience we deserve for different reasons.</p>
        </div>
        <div class="div">
            <p>We saw a gap between what people need and what banks offer. It means millions of us aren't getting the banking experience we deserve for different reasons.</p>
            <p>Traditional banks don’t focus on customers' experience, their systems may be slow and outdated, they may prioritize a specific group of people, or perhaps they lack the ability to innovate, and so on.</p>
            <p>We saw a gap between what people need and what banks offer. It means millions of us aren't getting the banking experience we deserve for different reasons.</p>
            <p>Traditional banks don’t focus on customers' experience, their systems may be slow and outdated, they may prioritize a specific group of people, or perhaps they lack the ability to innovate, and so on.</p>
            <p>We saw a gap between what people need and what banks offer. It means millions of us aren't getting the banking experience we deserve for different reasons.</p>
        </div>
        <div class="div">
            <p>We saw a gap between what people need and what banks offer. It means millions of us aren't getting the banking experience we deserve for different reasons.</p>
            <p>Traditional banks don’t focus on customers' experience, their systems may be slow and outdated, they may prioritize a specific group of people, or perhaps they lack the ability to innovate, and so on.</p>
            <p>We saw a gap between what people need and what banks offer. It means millions of us aren't getting the banking experience we deserve for different reasons.</p>
            <p>Traditional banks don’t focus on customers' experience, their systems may be slow and outdated, they may prioritize a specific group of people, or perhaps they lack the ability to innovate, and so on.</p>
            <p>We saw a gap between what people need and what banks offer. It means millions of us aren't getting the banking experience we deserve for different reasons.</p>
        </div>
        <div class="div">
            <p>We saw a gap between what people need and what banks offer. It means millions of us aren't getting the banking experience we deserve for different reasons.</p>
            <p>Traditional banks don’t focus on customers' experience, their systems may be slow and outdated, they may prioritize a specific group of people, or perhaps they lack the ability to innovate, and so on.</p>
            <p>We saw a gap between what people need and what banks offer. It means millions of us aren't getting the banking experience we deserve for different reasons.</p>
            <p>Traditional banks don’t focus on customers' experience, their systems may be slow and outdated, they may prioritize a specific group of people, or perhaps they lack the ability to innovate, and so on.</p>
            <p>We saw a gap between what people need and what banks offer. It means millions of us aren't getting the banking experience we deserve for different reasons.</p>
        </div>
        <div class="div">
            <p>We saw a gap between what people need and what banks offer. It means millions of us aren't getting the banking experience we deserve for different reasons.</p>
            <p>Traditional banks don’t focus on customers' experience, their systems may be slow and outdated, they may prioritize a specific group of people, or perhaps they lack the ability to innovate, and so on.</p>
            <p>We saw a gap between what people need and what banks offer. It means millions of us aren't getting the banking experience we deserve for different reasons.</p>
            <p>Traditional banks don’t focus on customers' experience, their systems may be slow and outdated, they may prioritize a specific group of people, or perhaps they lack the ability to innovate, and so on.</p>
            <p>We saw a gap between what people need and what banks offer. It means millions of us aren't getting the banking experience we deserve for different reasons.</p>
        </div>
        <div class="div">
            <p>We saw a gap between what people need and what banks offer. It means millions of us aren't getting the banking experience we deserve for different reasons.</p>
            <p>Traditional banks don’t focus on customers' experience, their systems may be slow and outdated, they may prioritize a specific group of people, or perhaps they lack the ability to innovate, and so on.</p>
            <p>We saw a gap between what people need and what banks offer. It means millions of us aren't getting the banking experience we deserve for different reasons.</p>
            <p>Traditional banks don’t focus on customers' experience, their systems may be slow and outdated, they may prioritize a specific group of people, or perhaps they lack the ability to innovate, and so on.</p>
            <p>We saw a gap between what people need and what banks offer. It means millions of us aren't getting the banking experience we deserve for different reasons.</p>
        </div>
    </body>
    </html>

    Note:

    The background images can load a little bit slow because of the size. It is recommended to store up your background images in the local.