When I scroll, changing the position from fixed to absolute causes my image to jump

My goal is to implement a unique visual effect where a background image, initially positioned as "fixed", gradually moves towards the top of the webpage and then disappears as if it were absolutely positioned. However, this movement should only occur after a specific number of pixels have been scrolled.

Currently, I have utilized the "addClass" event to switch the positioning from fixed to absolute when the desired pixel threshold is reached.

However, upon reaching the specified pixel count, the image instantly jumps to its absolute position instead of smoothly transitioning upwards from its current fixed position. I aim to change this behavior so that the movement starts from the image's current position.

Below is the JQuery code responsible for this functionality:

   <script>
       $(document).on("scroll", function () {
var pixels = $(document).scrollTop()
if (pixels > 350) { 
$("img").addClass("scrolled")
} else {
$("img").removeClass("scrolled")
}
})
    </script>

UPDATE I will now provide the HTML and CSS code for better clarity. I apologize for not including these essential details in my initial query.

HTML

<div class="grid"> <div class="row"><div class="col-6"><img src="https://www.illibraio.it/wp-content/uploads/2017/09/francesco-carofiglio-1.jpg" alt="FotoPortfolio"></div></div>


        <div class="row">
     <p class="page">
      Hi everybody!<br>
      My name is Francesco Cagnola<br> and I'm a communication designer.<br>
   Recently, I've graduated at Politecnico di Milano with a degree in Communication Design.
      I'm experienced in videomaking and photography but I can do beautiful graphics too.
        I'm based in Milan but I'm spending a period in London to breath this vibrant city!
         <br><br>
         "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.Sed ut perspiciatis unde omnis iste natus error sit voluptatem accusantium doloremque laudantium, totam rem aperiam, eaque ipsa quae ab illo inventore veritatis et quasi architecto beatae vitae dicta sunt explicabo. Nemo enim ipsam voluptatem quia voluptas sit aspernatur aut odit aut fugit, sed quia consequuntur magni dolores eos qui ratione voluptatem sequi nesciunt. Neque porro quisquam est, qui dolorem ipsum quia dolor sit amet, consectetur, adipisci velit, sed quia non numquam eius modi tempora incidunt ut labore et dolore magnam aliquam quaerat voluptatem. Ut enim ad minima veniam, quis nostrum exercitationem ullam corporis suscipit laboriosam, nisi ut aliquid ex ea commodi consequatur? Quis autem vel eum iure reprehenderit qui in ea voluptate velit esse quam nihil molestiae consequatur, vel illum qui dolorem eum fugiat quo voluptas nulla pariatur?"
    </p> 
    </div> </div>  

CSS

.grid {
   width: 100%;
}

.row {
    margin-bottom: 1%;
    display: flex;
    justify-content: flex-start;
}

.col-6 {
    width: 50%;
}

body {
  background-color: #000000;
  color:black;
 margin: 0px
}
img {    position: fixed;
    top:15%;
    justify-content: flex-end;
    margin-left: auto;
    width: 50%;
    right:5%;
    z-index: 0;
}
.scrolled{
  position:absolute;
}

.page {
  font-family: 'Roboto', sans-serif;
  font-size: 36px;
  font-weight: 400;
  color: white;
  position: absolute;
  top: 10%;
 padding: 14px 16px;
    width: 60%;
    float: left;
}

Answer №1

If you decide to remove the class called "scrolled", you could consider adding a new class named "animation" instead.

The "animation" class in CSS would look like this:

.animation {
    position: absolute;
    animation-name: godown;
    animation-duration: ...s;
    animation-fill-mode: forwards;
}

@keyframes godown {
    0% {
        top: 350px;
    }
    100% {
        top: 0px;
    }

For jQuery, you could use the following code:

if (pixels > 350) { 
    $("img").addClass("scrolled");
    $("img").removeClass("animation");
} else {
    $("img").removeClass("scrolled");
    $("img").addClass("animation");
}

Remember, the "scrolled" class must have the following CSS properties:

.scrolled {
    position: absolute;
}

Although I am currently testing on my mobile device, it seems like this setup should work as expected.

UPDATE: The CSS section includes the following styles:

.grid {
  width: 100%;
}

.row {
  margin-bottom: 1%;
  display: flex;
  justify-content: flex-start;
}

.col-6 {
  width: 50%;
}

body {
  background-color: #000000;
  color:black;
 margin: 0px
}
img {    
  position: fixed;
  top:15%;
  justify-content: flex-end;
  margin-left: auto;
  width: 50%;
  right:5%;
  z-index: 0;
}
.scrolled{
  position:absolute;
  animation-name: godown;
  animation-duration: .5s;
  animation-fill-mode: forwards;
}

.page {
  font-family: 'Roboto', sans-serif;
  font-size: 36px;
  font-weight: 400;
  color: white;
  position: absolute;
  top: 10%;
  padding: 14px 16px;
  width: 60%;
  float: left;
}

@keyframes godown {
0% {
    top: 350px;
}
100% {
    top: 0px;
}

For the JavaScript section, you can use the following code:

$(window).scroll(function(){
  $(document).on("scroll", function () {
  var pixels = $(document).scrollTop()
  if (pixels > 350) {
    $("img").addClass("scrolled");
  } else {
    $("img").removeClass("scrolled");
    }
  });
});

Upon testing, the code performs well, smoothly transitioning the image to absolute position when scrolled 350px from the top.

2nd update:

You can simulate the effect of "position: fixed" using jQuery. Here's a sample code snippet:

$(window).scroll(function () {
var pixels = $(document).scrollTop()
  if (pixels < 350) {
    $('img').css(
      'top', $(this).scrollTop() + "px"); 
  }  else {
        $('img').css(
          'top' : '0px',
          'transition' : '.5s');
      }
});

In the CSS section, you can define the "img" styling as follows:

img {
  position: absolute;
}

Answer №2

Adding a position relative in the CSS for images that lack top, left, right, and bottom properties can easily resolve the issue. It is important to ensure that both the HTML and CSS files are properly structured.

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

When referencing a particular React commit in package.json, it may result in the installation of react-tools instead of react itself

After including the following line in my package.json: "react": "git://github.com/facebook/react.git#08e4420019f74b7c93e64f59c443970359102530" When I execute npm install, I notice that node_modules/react-tools has been installed instead of node_modules/r ...

What is the correct way to dynamically switch between RTL and LTR in React with Material UI?

I recently learned that in order to support right-to-left (RTL) languages with Material UI, you need to follow these steps. I have a select input that allows users to switch between languages, changing the overall direction of the app. The core of my appl ...

Is it acceptable to utilize a UUID as an HTML tag ID without encountering any problems?

I need to handle dynamic content accessible through an index on a side panel. When a user selects an element from the side panel, I use the ID to determine which data they're requesting so that I can generate the corresponding content for the main sec ...

Unable to access local JSON file data in React.js

I have been struggling to retrieve data from a JSON file located within my ReactJS project directory. Even attempting to access the package.json file within the ReactJS folder resulted in errors. How can I successfully extract data from a local JSON file ...

The getimagesize functionality seems to be malfunctioning

I have developed a function that resizes images to fit as a background image for a div. I provide the function with the div size and the image path. It works perfectly when the height is larger than the width, but it fails when the width is larger than the ...

Creating numerous strings using template literals

I am looking to create multiple strings using a template literal and an array variable. For instance, a template literal allows you to replace an expression with its content in a string: var = "world"; tpl = `Hello ${var}!`; console.log(tpl); // Hello wor ...

A guide on showcasing specific data within ng-repeat by referencing another property in JSON object

After retrieving a JSON file using $http(), the structure looks something like this: [ { "sno": "3", "eventname": "hockey", "event-type": "sports", "A-team": "mme", "B-team": "eee", "Gender": "male", "time": "2017-11-24 00:00:00", "isres ...

Storing dynamic content on a server and retrieving it for future use

I'm working on a webpage that allows users to create elements dynamically and I want to save those elements to the server. When someone else visits the page, I want them to see those saved elements as well. I'm not too familiar with web programm ...

The fillOpacity and opacity properties appear to be malfunctioning

Note: While I understand that image masking can solve my issue, I prefer not to use it as it would require me to use my image as a background and could present accessibility challenges. I am specifically looking for solutions involving clip-path. Issue: T ...

Can studying Titanium Appcelerator enhance my comprehension of NodeJS?

As I dive into the world of building mobile JavaScript Applications in Titanium Appcelerator, I've come across documentation that mentions the use of the V8 Engine as their JS interpreter for Android. Additionally, some of the approaches seem to be in ...

Having trouble navigating through multiple layers of nested array data in react js

I need help understanding how to efficiently map multiple nested arrays of data in a React component and then display them in a table. The table should present the following details from each collection: title, location, description, and keywords. Below ...

What steps do I need to take to create npm packages specifically for react-native development?

Which programming languages are essential for creating npm packages that work on both android and ios platforms in react-native development? Can you suggest any helpful documentation or blogs for developing npm packages that support ...

Obtain the Class Name Value by Utilizing the "Begins With" Selection Method

Consider the following HTML structure: <a href="#" class="a b nl-3522">First</a> <a href="#" class="a b nl-7352">Second</a> <a href="#" class="a b nl-4874">Third</a> <!-- Note that classes nl-* are being added dynami ...

What are the mechanics behind the functionality of ES6 class instance variables?

I'm encountering an issue with the following code that is not behaving as expected: import React, { Component } from 'react'; let result = null; class MyData extends Component { _getData = () => { fetch(url) .then(response = ...

I'm having trouble grasping the concept of serving gzip-compressed JavaScript and CSS files

Why is it important to serve compressed JavaScript and CSS files? I understand that it reduces file size, but does the browser/webserver have to decompress them to read them? It's been mentioned that the webserver handles the compression. Does this me ...

Loop through the <li> elements and use jQuery to update the text

Check out this HTML setup: <div class="mydiv"> <ul> <li>Text 1</li> <li>Text 2</li> </ul> <ul> <li>Text 3</li> <li>Text 4</li> </ul> <ul> < ...

Dealing with redirecting to the login page in Angular

I recently started working with Angular and I feel completely lost. My initial task involves making a simple Rest-GET request, but the destination is located behind an external login page. This results in my request being redirected to the external page a ...

Getting the URL path within getStaticPaths in Next.js

Is there a way to retrieve the last number from the current URL pathnames in getStaticPaths? http://localhost:3000/category/food/2 -> 2, http://localhost:3000/category/food/3 -> 3, ... I have attempted: export const getStaticPaths: GetStaticPaths = ...

Encountered a problem during the insertion of data into the database through ajax and php

An issue is being encountered while trying to insert data into a database using Ajax, PHP, and jQuery. The code works smoothly on a localhost environment, but upon uploading it to the server, an error occurs. $('#sunsubmit').click(function(){ ...

Effective approach to exchange information among controllers in AngularJS

There are numerous techniques available to share data between controllers in Angular, such as accessing prototypical data from a parent scope, utilizing scope events for controller communication, or implementing shared services. However, what is considere ...