Troubleshooting the problem of divs overlapping when scrolling in JavaScript

I am experiencing some issues with full screen divs that overlay each other on scroll and a background image. When scrolling back to the top in Chrome, the background shifts down slightly, and in Safari, the same issue occurs when scrolling down. I have created a fiddle here to demonstrate this behavior. You can see how the panel content overlaps after scrolling up again, creating different effects in Chrome and Safari.

The problem seems to be caused by the background-image animation. Without it, everything works fine.

#bg {
  background-image: url('https://unsplash.it/800?random');
  background-size: cover;
  z-index: -1;
  animation: zoom 10s;
  height: 100%;
  width: 100vw;
  position: absolute;
  -webkit-animation-fill-mode: forwards;
  background-attachment: fixed;
}

@keyframes zoom {
  0% { transform:scale(1,1); }
  100% { transform:scale(1.1,1.1);}
}

I am looking for a solution to use the animation while maintaining the desired effects on the page.

This is the HTML code:

<body>
  <div id="bg">
  </div>
  <div class="panel panel-one">
    <div class="panel-inner">
        <h1>Lorem ipsum dolor sit amet</h1>
        <p>Donec id ipsum odio. Cras accumsan consectetur nibh, vitae pretium dui hendrerit sed. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Sed ac orci elit. Nunc faucibus eros vulputate purus aliquam vel blandit ligula pharetra.</p>
    </div>
</div>

<div class="panel panel-two">
    <div class="panel-inner">
        <h2>Lorem ipsum dolor sit amet</h2>
        <p>Donec id ipsum odio. Cras accumsan consectetur nibh, vitae pretium dui hendrerit sed. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Sed ac orci elit. Nunc faucibus eros vulputate purus aliquam vel blandit ligula pharetra.</p>
    </div>
</div>

<div class="panel panel-three">
    <div class="panel-inner">
        <h3>Lorem ipsum dolor sit amet</h3>
        <p>Donec id ipsum odio. Cras accumsan consectetur nibh, vitae pretium dui hendrerit sed. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Sed ac orci elit. Nunc faucibus eros vulputate purus aliquam vel blandit ligula pharetra.</p>
    </div>
</div>


</body>

And here is the script handling the scrolling:

$(function() {

    // Set up variables
    var _window = $(window),
        panels = $('.panel'),
        panelsY = [];

    // Cache the position of each panel
    $.each(panels, function(i, el) {
        panelsY.push(panels.eq(i).offset().top);
    });

    // Bind our function to window scroll
    _window.bind('scroll', function() {
        updateWindow();
    });

    // Update the window
    function updateWindow() {
        var y = _window.scrollTop();

        // Loop through our panel positions
        for (i = 0, l = panels.length; i < l; i++) {
            /*
                Firstly, we break if we're checking our last panel,
                otherwise we compare if the y position is in between
                two panels
            */
            if ((i === l - 1) || (y >= panelsY[i] && y <= panelsY[i+1])) {
                break;
            }
        };

        // Update classes
        panels.not(':eq(' + i + ')').removeClass('panel-fixed');
        panels.eq(i).addClass('panel-fixed');
    };

});

Answer №1

Modifications were made by adding margin: 0 to the html, body rule and switching to position: fixed for #bg.

Do you think this revised fiddle will function correctly?

Changes in CSS styling are evident

#bg {
  background-image: url('https://unsplash.it/800?random');
  background-size: cover;
  z-index: -1;
  animation: zoom 10s;
  height: 100%;
  width: 100vw;
  position: fixed;
  -webkit-animation-fill-mode: forwards;
  background-attachment: fixed;
}

@keyframes zoom {
  0% { transform:scale(1,1); }
  100% { transform:scale(1.1,1.1);}
}

html, body {
  margin: 0;
  height: 100%;
}

If not successful, consider trying to animate the background size rather than scaling as a potential solution

Updated version of the fiddle

CSS has been altered

#bg {
  background: url('https://unsplash.it/800?random') no-repeat center center fixed;
  background-size: 100% 100%;
  z-index: -1;
  animation: zoom 10s;
  height: 100vh;
  width: 100vw;
  position: absolute;
  -webkit-animation-fill-mode: forwards;
}

@keyframes zoom {
  0% { background-size: 100% 100%; }
  100% { background-size: 120% 120%;}
}

html, body {
  margin: 0;
  height: 100%;
}

Answer №2

The issue lies within the 'body' element. Kindly incorporate this code into your CSS stylesheet.

body {
    padding: 0;
    margin: 0;
} 

It is recommended to utilize a CSS reset snippet for optimal styling consistency.

Trust this solution proves beneficial.

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

A step-by-step guide to implementing Inline Linear Gradient in Nuxt/Vue

How can I create a linear gradient overlay on top of my inline background image? I attempted to add a CSS style but the class seems to be positioned beneath the image. <div class="header__bkgd" v-bind:style="{'background-image': 'url(&ap ...

What's the best way to ensure that the iframe resolution adjusts dynamically to perfectly fit within its container?

iframe-screenshot Displayed in the image are two iframes, but at times I may need to display three. The aim is to ensure that all iframes are responsive within their containers. Below is my existing CSS styling: iframe { width: 100%; height: 1 ...

A step-by-step guide on making an animation series with html and css keyframes

I've been working on creating a captivating animation using HTML and CSS keyframes, but I seem to have hit a roadblock. Despite trying different rotations and transforms, I can't seem to achieve the desired effect depicted in the image below. The ...

Navigating through the nested object values of an Axios request's response can be achieved in React JS by using the proper

I am attempting to extract the category_name from my project_category object within the Axios response of my project. This is a singular record, so I do not need to map through an array, but rather access the entire object stored in my state. Here is an ex ...

Implementing the array name property in a JSON object using ES5

I am currently working with a JSON object that has the following structure: {"Firstname":"john","Lastname":"doe"} My goal is to transform it into an array with a specific name 'abc': users: [{"Firstna ...

What is the best way to create a list from a matrix using JavaScript?

I have an array structured as follows: const input_array= [ ["red", "green"], ["small", "medium"], ["x", "y", "z"] //... can have any number of rows added dynamically ...

While in Safari, there seems to be a random issue where the embedded image in an SVG becomes blank when using the Canvas API to convert it to

My current approach involves generating a png from a valid svg string that contains an embedded image. The code snippet below illustrates this: <image xlink:href="data:image/png;base64,..." x="0" y="0" width="362" ...

A comprehensive guide on implementing form array validations in Angular 8

I am currently using the formArray feature to dynamically display data in a table, which is working perfectly. However, I am facing difficulty in applying the required field validation for this table. My goal is to validate the table so that no null entry ...

Discovering dependencies for the Tabulator library can be achieved by following these

Can anyone provide me with a complete list of dependencies for Tabulator 4.2? I have already reviewed the package.json file, but it only contains devDependencies. ...

Ways to customize easypiechart appearance with CSS styling

I am looking to create a circular counter similar to the one shown below. I have tried using easy-pie-chart but I am unsure how to style the circles to look like the example provided. Is there a way to achieve this through CSS? Any recommended resources o ...

jQuery does not trigger background image change in Webkit

const displayPreviewImage = (imageUrl) => { $('#slideshow-container').css("background-image", `url('files/images/store/content/templates/websites/preview_images/${imageUrl}'`); } I have a function here th ...

There was an uncaught error in AngularJS stating that the URL in the HTTP request configuration must be a string

I've been working on a web application and have encountered some challenges. One particular issue I'm struggling with is related to the following code snippet: this.bookSpace = function (date, spaceId) { swal({ title: "Are you sure?", t ...

The total sum of various divs containing a mix of numbers and letters

I have a group of div elements with the same class, each containing a value in the format (X1), (X2),... I need to add up these numeric values only, like 1 + 2 + .... Since these divs are generated dynamically, I won't know how many there will be. How ...

Adjust the CSS border to finish at a 90-degree angle rather than a 45-degree angle

The div I'm working with has unique colors for the border-bottom and border-right properties, creating a diagonal line that separates the box at a 45 degree angle. I'm looking to adjust the bottom-border to be shorter in order for the right bord ...

TS2307 Error: The specified module (external, private module) could not be located

I have come across similar queries, such as tsc throws `TS2307: Cannot find module` for a local file . In my case, I am dealing with a private external module hosted on a local git server and successfully including it in my application. PhpStorm is able ...

Error 504 occurs on Express.js due to a timeout issue while a timer is active

Encountering a "504 Gateway Timeout" error on my Express.js application when a JavaScript timer is set to run every 20 seconds. Here is the code for my Express.js listener and the timer: const express = require('express') const app = express() ...

Printing keys of objects in an array in AngularJS through iteration

Here is an array of objects that I am attempting to iterate in ng-repeat and print keys, but I am facing some challenges. $scope.directivesInfo = [ {"ngRepeat": {"enter": true, "leave": true, "move": true, "add": false, "remove": false}}, {"ngView ...

Switch back JSON in php script

After receiving a JSON object with an unspecified number of key/value pairs, I need to send it from my $.ajax function to a PHP script. The PHP script must then revert the JSON object and send it back to jQuery. {"First name": "John", "Contact": "2323",.. ...

Utilizing NextJS to Call the Layout Component Function from the Page Component

I can't seem to find an answer to this question for Next.js after searching online. While there are solutions available for React, I don't think they will work in the Next.js framework. My application is essentially a shop with a navigation menu ...

Using Vue.js code on an HTML file is only possible when the necessary CDN is included

Just diving into Vue.js and I've got a header html that doesn't include the cdn link for Vue.js. <nav class="navbar navbar-toggleable-md navbar-inverse"> <div class="collapse navbar-collapse" id="navbarSupportedContent"> ...