Switching effortlessly between Fixed and Relative positioning

As I work on creating a unique scrolling experience, I aim to have elements stop at specific points and animate before returning to normal scroll behavior once the user reaches the final point of the page.

Essentially, when div X reaches the middle of the screen, it will become fixed in position, allowing for animations such as expansion or movement. Once the user scrolls to the end, it reverts back to a relative position while staying in place.

In a previous prototype, I manually determined the point where the element should start animating by measuring its position on the screen using a browser ruler and fixing its position statically from there. However, this approach is cumbersome and inefficient.

One potential solution involves dynamically calculating the Y position based on the scroll and summing up values. Although, adjusting the x position for responsiveness poses challenges.

How can JavaScript facilitate this change? How can we dynamically determine the fixed equivalent position of a relative element?

While my JS experience is limited, I am confident that effective solutions exist for this scenario.

Answer №1

Utilizing JavaScript to instantly adjust the position (x,y) and the position (absolute/fixed) seems like the ideal solution. There may also be a library available for this purpose, but here is a rough outline of a potential solution:

var div = document.querySelector(".dog");
var div_status = document.querySelector("#div_status");
var start = 100;
var stop = 800;
var swap = false;
window.addEventListener("scroll", function() {
  var y = window.scrollY
  var rect = div.getBoundingClientRect();
  div_status.innerText = rect.top.toFixed() + " " + y.toFixed()
  if (y >= start && y <= stop) {

    div_status.style.background = "green"
    if (!swap) {
      div.style.position = "fixed";

      div.style.top = rect.top + "px"
      swap = true
    }
  } else {
    div_status.style.background = "red"
    if (swap) {

      div.style.position = "absolute";
      div.style.top = (y + rect.top) + "px"
      swap = false;
    }

  }
})
body {
  height: 2000px;
}

.dog {
  height: 50px;
  width: 200px;
  border: 1px solid gray;
  background: lightyellow;
  line-height: 50px;
  text-align: center;
  position: relative;
}

#div_status {
  background: red;
  color: white;
  position: fixed;
  right: 100px;
}
<body>
  <pre id="div_status">0 0</pre>
  <br>
  <br>
  <br>
  <br> keep scrolling
  <br>
  <br>
  <br>
  <br>
  <br>
  <br>
  <br>
  <div class="dog">Dog</div>

</body>

Answer №2

After doing some research, I found a solution to my own problem by using the position:sticky property in CSS. It turned out to be a very simple and seamless fix.

#wrap{
    margin:15px;
    padding:10px;
}


.d1{
    
    width:400px;
    height:500px;
}


#d2{
    //background-color:red;
    height:900px;
}


#d3{
  width:100px;
    height:50px;
    border: 10px solid black;
    background-color:green;
    position: sticky;
    top: 70px;
}
<body>

<div id="wrap">
    <div class="d1"><div>Scroll Down</div></div>

    <div id="d2" >
        <div id="d3" class="content">I'm the guy...</div>
    </div>

    <div  class="d1"><div>
  <br/><br/><br/><br/><br/><br/><br/><br/>
  <br/><br/><br/><br/><br/><br/><br/>
  Scroll Up</div></div>

</div>
</body>

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

The functionality of sending a response to a client in Node.js Express seems to be malfunctioning

I am facing an issue with sending a response back to the client. Despite not receiving any errors, it seems like the response is not working as expected. Can anyone help me figure out why? Below is my code snippet: exports.login = function (req, res, next ...

JavaScript: Invoking a nested function within a namespace

script1.js var MyNamespace = {}; MyNamespace.addNewFunction = function(a,b,c) { function doSomething() { // Perform some action here } } script2.js MyNamespace.addNewFunction.doSomething() ?? I’m a bit unsure on how to access the content ...

URL relative references across multiple domains

Here's a quick question: When developing themes and coding, how do you navigate linking to different files in your html/css code? For example: At our company, we mostly use <base target="http://whatever"> in our main template and then simply r ...

Waiting for all promises to resolve: A step-by-step guide

I need to make two different API calls and perform calculations based on the results of both. To wait for both promises to resolve, I am using Promise.all(). const getHashTagList = async () => { loader.start(); try { await getAllHashTag ...

Unable to retrieve HTML code from a webpage using its URL address

Currently, I am trying to retrieve the HTML code of a specific webpage located at . My initial attempts using HttpClient were unsuccessful due to exceeding request processing time. It seems like this website may have anti-bot protection in place. I attempt ...

Bootstrap modal experiencing technical difficulties

I am experiencing issues with my bootstrap modal. It seems to be malfunctioning, almost as if the CSS or JavaScript files are not being recognized. I have tried various solutions but have been unable to resolve the problem. I even attempted using the examp ...

The wrapper is failing to extend the full height of the entire page

Initially, I thought setting the height of my wrapping div to 100% would be a quick task that I could complete in five minutes. However, it ended up taking me hours, so now I'm here hoping someone can assist me with this commonly asked question. The ...

Updating a React component upon pressing a button to trigger a re-render

Currently, I am in the process of developing a React component that allows users to input an ID and retrieve relevant information upon submission. The code for this component is structured as follows: export default class IDContainer extends React.Componen ...

Form on the internet with a following button

Currently working on a basic form: <tr> <td> <label for="FirstName">First Name <span class="req">*</span> </label> <br /> <input type="text" name="FirstName" id="FirstName" class="cat_textbox" ...

What could be causing my code to fail in the useEffect hook every time I make updates to my JSON

I have a function that receives JSON data from the server. Using the {jsonData.map((element) => renderComponents(element, jsonData))} function, I loop through the data and send each object to the renderComponents function along with the full JSON data. ...

spacing between elements vertically

             I am struggling with a common issue and despite searching, I have not been able to find a solution that works for me. Here is my setup: <div id="wrapper">   <div class="content-area-top"></div>   <div clas ...

Challenges with parsing JSON using jQuery

I am attempting to retrieve data from a page that returns JSON in order to store it in an array. The current code is functional, but I am encountering difficulties when trying to pass the variable (which should contain the content) into the jQuery.parseJSO ...

Passing data to an Angular directive

I am facing an issue while trying to pass information through a view in a directive. Despite binding the scope, I keep seeing the string value 'site._id' instead of the actual value. Below is the code for the directive: angular.module('app ...

Converting MSK time to SST time using JavaScript: A Handy Guide

My API returns time in the format: 07:00 PM This timestamp is based on MSK (Moscow Standard Time) and I need it converted to SST (Singapore Standard Time) using either JavaScript or an npm package. ...

An error occurred with Express and Passport: ['ERR_HTTP_HEADERS_SENT']

Currently, I am diving into an ebook tutorial and have encountered a roadblock in a particular piece of code. The code is designed to take a username and password in JSON format through Insomnia or Postman, and it should return a login success cookie. Howe ...

The background color in CSS frames the text with a unique hue

Is there a way to wrap my multi-line text inside a div with a background color that automatically adjusts its size based on the text length? .multiline{ padding:0px; white-space: pre-wrap; height: 100px; width: ; margein:0px } <div style="b ...

What is the best way to store multiple values in local storage using useState in react?

Currently, I am exploring how to utilize multiple values in the useState hook and perform CRUD operations in local storage. Here is an example of my code: const [Data,setData]=[[{ name:'luis', pass:'1234', //....... }]] // ...... ...

Tips for showcasing two pieces of content next to each other across the entire webpage using a combination of Bootstrap, CSS, and Laravel

I am facing a challenge with displaying two contents side by side on a full page and stacking them vertically when the screen size is small (mobile). I have managed to achieve the side by side display on a full page, but they stack on top of each other on ...

Struggling to grasp the concept of using z-index in CSS

As a programmer versed in Python, C, Java, and Delphi, I am not a web developer or designer by trade. However, when required to fill those roles, I do my best; please be patient with me. :-) I have created a map (with a background image as a div), where I ...

Converting PHP variables to JavaScript using AJAX and XML communication

In order to gain a deeper understanding, I am determined to tackle this task without relying on jQuery. This means I am willing to reinvent the wheel in order to fully comprehend how it functions. My research has led me to believe that AJAX is the key to a ...