background image alteration when scrolling

I've been attempting to change the background image on scroll, but I haven't had any luck finding a guide. So, I'm hoping someone here can help me out. I found a video that showcases exactly what I'm trying to accomplish - https://www.youtube.com/watch?v=7u1aIxQCIXg. My goal is to have a background image with text overlay that changes or fades when scrolled to a certain point, rather than just moving up from the bottom. I've tried some things, but my skills aren't quite there yet.

Answer №1

Even though there was no information on the progress you made, I still enjoyed working on it. If you find my solution useful, please consider accepting my answer and take a look at my demo on CodePen.

<style>
    body {margin: 0;padding: 0;}
    .section {
        height: 100vh;
        width: 100%;
        display: flex;
        z-index: 1;
        position: relative;
        background-size: 100% 100% !important;

    }
    .text {
        margin:auto;
        font-size: 2.5em;
        border:1px solid white; 
        color:white;
        padding:1em;
        text-shadow: 2px 2px 3px black,
                     2px 2px 3px black;        
    }
    .BG {
        position: fixed;
        z-index: 0;
        opacity: 0.4;
        transition: opacity 0.3s ease;
    }
    .anim {opacity:1;}
    .show {color:orange;}
</style>
<body>
<div class="main">
    <div class="section BG">
        <div class="show"></div>
    </div>
    <div class="section" BGurl="https://i.ibb.co/0DxzSg0/pngtree-blue-carbon-background-with-sport-style-and-golden-light-image-371487.jpg"><div class="text">SECTION</div></div>
    <div class="section" BGurl="https://i.ibb.co/31YPsfg/triangles-1430105-340.png"><div class="text">SECTION</div></div>
    <div class="section" BGurl="https://i.ibb.co/Y3BgqMc/7f3e186790208b63dadda09d6b91d334.jpg"><div class="text">SECTION</div></div>
    <div class="section" BGurl="https://i.ibb.co/GCQP61b/photo-1513151233558-d860c5398176-ixlib-rb-1-2.jpg"><div class="text">SECTION</div></div>
    <div class="section" BGurl="https://i.ibb.co/D9WGPf9/pngtree-modern-double-color-futuristic-neon-background-image-351866.jpg"><div class="text">SECTION</div></div>
</div>
</body>

<script>
    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

</script>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

After the submit button is disabled, the form fails to be submitted

Hello, I am having an issue with disabling my button after the form is submitted. The button gets disabled, but the PHP code does not execute. I have tried various scripts from the internet, but they all seem to have the same result: the button gets disab ...

What is the best way to arrange an array or display it accurately?

Guys, here's a challenge for you: extract the values from this JSON data: [[name, brand, oem, category], [name, brand, oem, category], [name, brand, oem, category], [name, brand, oem, category]] Check out my JavaScript code: $(function(){ $('i ...

Comparing Two Items between Two Arrays

I have a scenario where I need to compare values in two arrays by running a condition. The data is pulled from a spreadsheet, and if the condition is met, I want to copy the respective data. For instance, I aim to compare two cells within a spreadsheet - ...

"Maximizing the functionality of HTML forms by incorporating PHP for efficient data retrieval

I have been exploring different approaches but I'm struggling to get this to function correctly. As a beginner, I am using form elements with dropdown menus to receive user input and then send the data via email. Here is the HTML and PHP code: <fo ...

Creating CSS styles to ensure text takes up the largest size possible without wrapping or extending beyond the screen borders

Looking for a way to display text at its maximum size without any wrapping or overflowing the screen? I attempted using @media and adjusting font-size, but things got too complex. My goal is to have the text on example.com displayed at the largest possible ...

The efficiency of React Context API's setters is remarkably sluggish

I have a goal to implement a functionality where the background gradient of a page changes depending on whether the child's sublinks are expanded or collapsed. To achieve this, I am using the useContext hook. However, I've noticed that although e ...

Most effective method to avoid updating a node_modules package

tag: After downloading and installing a node_module (npm package)... I have customized the internal files within the node_modules folder to better fit my requirements. Although using it as a node_module is most convenient for me, I am concerned that futur ...

API Post request encountering fetch failure

The route "/api/users/register" on my express server allows me to register an account successfully when passing data through Postman. However, when trying to register an account using the front-end React app, I'm encountering a "TYPE ERROR: Failed to ...

Menu with full-width navigation and dropdown options

I am trying to create a navigation menu with a black background that spans the full width of the window. To achieve this, I have placed the ul element inside a div with overflow: hidden; set. However, I am facing issues where hovering over submenus causes ...

Tips for correctly deleting a duplicate ref Object ID following the removal of a Document

Coming from a background in relational databases, I'm encountering a challenge with a pattern in Mongoose. Let's say we have SchemaA and SchemaB (for example, pets and people): const Person = new Schema({ name: String, pets: [{ ref: ...

Unusual sidebar scrolling issues experienced in Firefox

Currently, I am in the process of developing an app with a scrolling sidebar. However, there seems to be some unexpected behavior when using Firefox: the content within the sidebar disappears partially below the top of the div if the mouse is positioned lo ...

Email notification will be sent upon form submission to Firestore

I'm currently designing a website for booking reservations through an HTML form, with data submission to firestore. Upon submission, a confirmation email is sent to the customer. Below is the code snippet I am using to achieve this: var firestore = fi ...

ShadowBox not displaying Vimeo videos

I can't figure out why my Vimeo videos are not appearing in a Shadowbox. I have followed the steps I know to be the simplest, which involve copying the example directly from the github page and then updating the shadowbox paths to match the locations ...

Personalized path-finding tree iterator

I am trying to implement a custom iterator in JavaScript that can traverse a DOM tree based on specific criteria provided by a callback function. The goal is to return an array of the nodes that match the criteria as the generator iterates through the tree ...

What happens when the overflow-hidden property is overlooked due to a child element being assigned absolute positioning?

When does overflow hidden not work as expected? If a child element overflows and has absolute positioning If the parent with overflow hidden is statically positioned When a second parent wrapper with relative positioning is added Why does this happen eve ...

The 'SVGResize' or 'onresize' property is not available on the 'SVGProps<SVGSVGElement>' type

Using React with SVG I'm facing an issue with handling the resizing event of an svg element. I have looked into using the SVGResize and onresize events, but encountered compilation errors when trying to implement them: const msg1 = (e: any) => co ...

Embedding a PDF file into an HTML form

For days, I have been on a relentless search for a solution to my problem to no avail. My ideal scenario involves embedding a fillable pdf form into an intranet html form for submission to the server, with the ability to parse field/values being a bonus b ...

A guide on effectively mocking functions in Jest tests with Rollup.js

I am currently in the process of developing a React library called MyLibrary, using Rollup.js version 2.58.3 for bundling and jest for unit testing. Synopsis of the Issue The main challenge I am facing is with mocking a module from my library when using j ...

Using Sweetalert2 to send data via AJAX POST request

Recently, I've been incorporating SweetAlert2 into my project and I want to create an "Add Note" feature. The process involves the user clicking a button, being directed to a page, and then the following script is executed: <script>swal({ ...

Using CSS styling to dictate how browsers display web content, specifically through setting font size measurements in EM

On different mobile devices and various browsers such as Internet Explorer and Mozilla, the font size in some divs does not appear consistent. Specifically, on a Samsung Galaxy S6. I am using EM units: I know it may not be ideal but I prefer this method a ...