Resolving problems related to window scrolling in javascript for implementing a "sliding door" style animation triggered by a scroll event

I am new to web development and I have been working on creating a portfolio website to learn. I have seen some websites with really cool effects on their landing pages and I would like to incorporate something similar into my site.

Specifically, I am interested in creating a "sliding door" effect. Instead of the page scrolling when the site loads, I want two divs to slide apart, revealing the content inside. I have somewhat achieved this, but I can't seem to make the content on the page remain static while the user scrolls to open the doors.

I have been trying to figure this out with JavaScript, but I haven't been able to find helpful resources online in a beginner-friendly format. I have created a demo of my progress in this jsfiddle since I couldn't figure out snippets. Here is also the JavaScript code I have been using:

window.addEventListener("scroll", handleScroll, {
  passive: false
});

let scrollPosition = 0;
const topCover = document.getElementById("top-cover");
const bottomCover = document.getElementById("bottom-cover");

function handleScroll(e) {

  e.preventDefault();

  scrollPosition = window.scrollY;
  const maxScroll = window.innerHeight / 2;

  if (scrollPosition < 0) scrollPosition = 0;

  topCover.style.transform = `translateY(-${scrollPosition}px)`;
  bottomCover.style.transform = `translateY(${scrollPosition}px)`;

  if (scrollPosition >= maxScroll) {
    cover.style.display = "none";
    window.removeEventListener('scroll', handleScroll)

  }
}

The two doors are the topCover and bottomCover divs, and they reveal upon scrolling down.

The issue I am facing is that the background content still scrolls, so the user would need to scroll back up to access the content after the doors disappear. I have tried using the wheel event instead, which prevents the background from scrolling, but it causes choppy animation when scrolling with the mouse wheel. Additionally, the wheel event doesn't account for scrolling with gestures or scrollbar movements, making it not ideal for my project.

Any assistance on how to resolve this problem would be greatly appreciated. I would prefer to stick to using vanilla JavaScript and CSS for this if possible.

Answer №1

After carefully reviewing your inquiry, I have made some adjustments in the fiddle you provided. Feel free to take a look and continue from there.

For those who are new to web development, Jquery can be a great tool for animations!

Here is the JavaScript code snippet:

window.addEventListener("scroll", handleScroll, {
  passive: false
});
const topCover = document.getElementById("top-cover"),
      bottomCover = document.getElementById("bottom-cover"),
      content=document.getElementById("content");
      maxScroll = window.innerHeight / 2;
function handleScroll(_e) {
  let scrollPosition = window.scrollY;
  if (scrollPosition < 0) scrollPosition = 0;
  if (scrollPosition < maxScroll) {
    topCover.style.height=bottomCover.style.height=`${maxScroll-scrollPosition}px`;
    content.style.marginTop=`${maxScroll}px`;
  } else {
    topCover.style.display=bottomCover.style.display="none";
    content.style.marginTop="initial";
    window.removeEventListener('scroll', handleScroll);
    window.scrollTo(0,0);
  }
}

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

Connecting Filters Vue.js

I am in need of chaining filters. My goal is to implement the following filters: - A search filter - A checkbox styled price filter with pre-defined values such as <$10, $20-$50, $50+ - A checkbox styled filter for selecting 'topics' ...

Performing multiple http requests in a loop and combining the retrieved data using AngularJS

I am currently working with a piece of source code that looks like this: var projectPromises = $http.get('http://myapi.com/api/v3/projects?private_token=abcde123456'); $q.all([projectPromises]).then(function(data) { console.log(data); ...

Tips for creating a concise switch statement in JavaScript, incorporating both the use of Express and Mongoose

Here's the current situation: I am tasked with searching in 3 different databases for an ID associated with a shift. Each shift is classified as either an Activity, Food and Beverages, or Other type. When making the search, the type is provided in t ...

Drop-down selection triggering horizontal auto-scroll

Within my div element, I have a table with dropdowns. The div is set up to be horizontally scrollable. To create the dropdown functionality, I utilized Harvesthq Chosen. Let me provide some context. In Image 1, you'll notice that I've scrolled ...

Why is the radio button getting bound to the error instead of the label?

I'm currently working on validating radio buttons in a GSP file using the jQuery validation plugin. The issue I'm facing is that the error message is being bound to the first radio button and appearing at the bottom of it. Instead of displaying ...

CSS: choose all elements starting from the n-th element and apply styles to them

Is it possible to choose specific child elements beyond the first few in a parent element? To clarify, let's say there's a div containing 7 spans. How can I select only the spans starting from the 3rd element onwards - so specifically span 4, 5, ...

Implementing a Beveled Edge on a Shape using ThreeJS

I have put in a lot of effort to find the solution, but unfortunately I have not been successful so far. Currently, I am working on creating a shape using THREE.Shape, and I have the vertices data stored in a file. The shape appears to be straight without ...

Looking to modify the contents of a shopping cart by utilizing javascript/jQuery to add or remove items?

I'm dealing with a challenge on my assignment. I've been tasked with creating a Shopping Cart using Javascript, HTML5, and JQuery. It needs to collect all the items from the shop inside an Array. While I believe I have most of it figured out, I a ...

error 404 when sending a xhr request in node and react js

I am currently developing a basic login page in React that needs to connect to a database through an AJAX call to a Node.js file. Here is the Node.js code I have implemented: var express=require('express'); var app=express(); var db=require(&ap ...

Validation on the client side for a form that is displayed within a bootstrap modal using ajax technology

Within my ASP.Net Core application, I am faced with the need to utilize validation on both the server side and client side in a bootstrap modal form. While I have successfully implemented server side validation, I have encountered difficulties when it come ...

Maintaining the active style of Asp.NET 4.0 Menu control even after the mouse is released

Utilizing a standard asp.net menu in an asp.net 4.0 web application, this setup is for a standard web application and not any version of MVC applications currently available. The issue at hand is relatively straightforward. CSS styles are applied to the d ...

Encountered an error in Next JS and Graph QL where attempting to destructure the property 'data' from an undefined intermediate value

I am encountering an issue while attempting to make a Apollo request to the SpaceX API. I am receiving a 500 (Internal Server Error) and also at getStaticProps. It's unclear whether this is a syntax problem or an error in my method of implementation. ...

`The Streaming module within React Native`

I am facing an issue in my React Native project where I want to use a node library that depends on stream (require('stream')). The problem arises with the error stream could not be found within the project because stream is a nodejs package not ...

What could be causing the issue of loading text not appearing in Vue.js?

I have the following code snippet in my application: <div id="app"> <button v-if="!isPrepared && !isLoading" @click="startLoading()">Start Loading</button> <div v-if="isLoading">Lo ...

Unable to render ng-view due to it being enclosed within a comment block

Currently, I am in the midst of developing a single page application which employs Node, Express, and Angular. The layout of my directory follows the typical format of an Express application <app> +--public +--routes +--views +--partials ...

Actions for jQuery's mouseenter and mouseleave events

I've implemented a jQuery script that controls the visibility of elements based on mouse events: $("#divid").mouseenter(function() { $('#divid').show(1000); }).mouseleave(function() { $('#divid').hide(1000); }); $("#hldiv" ...

Animated smooth updates in d3 line graphs are the key to creating dynamic and

I'm attempting to modify an example of Animated Line Graphs from: http://bl.ocks.org/benjchristensen/1148374 <div id="graph1" class="aGraph" style="width:600px; height:60px;"></div> <script> function draw(id, width, height, upd ...

Tips for triggering an error using promise.all in the absence of any returned data?

I'm dealing with an issue in my project where I need to handle errors if the API response returns no data. How can I accomplish this using Promise.all? export const fruitsColor = async () : Promise => { const response = await fetch(`....`); if( ...

Error: The function isInitial of chunk cannot be found

Currently, I am attempting to build my program using the following command: "build": "NODE_ENV='production' webpack -p", However, I encountered an error message: node_modules/extract-text-webpack-plugin/index.js:267 var shouldE ...

Instructions on integrating iframe into Slides on material-auto-rotating-carousel

Looking to swap out the carousel slide image with a loom video. Any ideas on how to replace the media img with an iframe in material-auto-rotating-carousel? const AutoRotatingCarouselModal = ({ handleOpen, setHandleOpen, isMobile }) => { return ( ...