Restore the images to their original state once the user scrolls back to the top

I have implemented 2 static images with fixed positions at the edges of the screen (one on the right and one on the left). The logic I want to achieve is that when a user scrolls more than 100 pixels from the top, these edge images should move back by 50 pixels. Moreover, I want them to return to their original position when the user scrolls back to the top. I attempted to use a boolean value which switches between true and false when the images retract or reappear, but it doesn't seem to be working as expected. Why?

userHasScrolled = false;

$(document).ready(function(){
 $(window).scroll(function(){
 if ($(window).scrollTop() > 100) {
  $(".rightstatic").animate({marginRight:'-50px'}, 900);
  $(".leftstatic").animate({marginLeft:'-50px'}, 900);
  userHasScrolled = true;
 }
 });
});

if($(window).scrollTop() <= 0 && userHasScrolled) {
  $(".rightstatic").animate({marginRight: '+50px'}, 400);
  $(".leftstatic").animate({marginLeft:'+50px'}, 400);
  userHasScrolled = false;
}

Edit:

$(document).ready(function(){
 $(window).scroll(function(){
   if ($(window).scrollTop() > 100) {
     $(".rightstatic").animate({marginRight:'-20px'}, 900);
     $(".leftstatic").animate({marginLeft:'-20px'}, 900);
   } else if($(window).scrollTop() <= 0) {
     $(".rightstatic").animate({marginRight: '+0px'}, 400);
     $(".leftstatic").animate({marginLeft:'+0px'}, 400);
   }
 });
});

Although this code somewhat works, there is a significant delay in the functionality. It takes more than a minute after reaching the top for the images to retract.

Edit 2: Finally, after throttling the function, it now operates smoothly. Thank you @TomaszBubała for the assistance.

Answer №1

The issue lies in the fact that the bottom part of your code is only called once, and at that time `userHasScrolled` is still `false`. To resolve this, you should combine both sections within the `$(window).scroll()` function. You can eliminate the need for the `userHasScrolled` variable and change the second condition to simply be an `else` statement instead of an `else if`.

var scrollTimeout;
var throttle = 250;
$(document).ready(function(){
 $(window).scroll(function(){
   if(scrollTimeout) return;
   scrollTimeout = setTimeout(function() {
     scrollTimeout = null;
     const scrolled = $(this).scrollTop();
     if (scrolled > 100) {
       console.log("1");
       $(".rightstatic").animate({marginRight:'-20px'}, 900);
       $(".leftstatic").animate({marginLeft:'-20px'}, 900);
     } else {
       console.log("2");
       $(".rightstatic").animate({marginRight: '+0px'}, 400);
       $(".leftstatic").animate({marginLeft:'+0px'}, 400);
     }
   }, throttle);
 });
});

Fiddle: https://jsfiddle.net/wctxbynt/41/

EDIT:

The original issue stemmed from the `scroll` event being triggered multiple times with a single mousewheel interaction, leading to excessive calls of jQuery animate. By implementing a throttling mechanism, we ensure that the scroll handler code is executed only up to 4 times per second. This improvement significantly enhances performance. Check out more about throttling here.

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

Ensure that the user's browser cache is cleared after deploying a new version on Firebase hosting

Utilizing create-react-app for my front end scripts and firebase hosting for deployment has been smooth overall. However, I've encountered an issue where updates to CSS and HTML files don't always reflect on the domain until I manually clear the ...

Invoking a class method in Javascriptcore on iOS

I'm currently trying to comprehend the inner workings of JavascriptCore. Initially, I attempted calling a single function. Now, my focus has shifted to invoking a function within a class. This is what my javascript code looks like: var sayHelloAlf ...

Creating a dynamic height sticky sidebar and footer in Bootstrap 5 using CSS/HTML

Looking to implement a sticky sidebar feature with a header and footer that remain visible while the middle content scrolls. The overall height of the page will vary, so I plan to use Bootstrap 5 grid for structuring. <!DOCTYPE html> <html la ...

Preventing incomplete file uploads (through FTP) while retrieving the latest file using ajax and PHP

Yes, the title of this may seem unusual, but there's a reason for it. In my setup, I have a camera linked to a laptop. Through Remote Shooting, when a photo is captured by the photographer, it gets stored in a folder on the laptop's hard drive. ...

Learning the process of connecting functions to events

// param {id:'buttonId', action : function(event[,param1, param2] ){}, behavior:function(event[,param1, param2] ){} } CustomButton = function(parameters) { var buttonElement = document.getElementById(parameters.id); // how c ...

Transforming a triangular shape into a square using Plane Geometry in THREE.js

I have an animation created with triangles in the link below. Is there a way to convert these triangular areas into squares? The animation currently has a line running through the middle when using "PlaneGeometry". Removing this line would turn the triangl ...

What is the best way to utilize webpack for transferring files to the distribution directory?

I am trying to figure out how to get webpack to automatically grab the necessary JS and CSS files and place them in the dist folder of my index.html without needing to require or import them. Any suggestions on how to accomplish this task efficiently? ...

Utilize Flexbox to create ample space on the right side

Hi there, I've noticed that when I use display: flex, the right side of my row seems to have a slight gap. How can I go about fixing this issue? It's not very obvious in jsfiddle, but you can spot it using Firebug or a similar tool. Check out th ...

Using Web SQL always seems to throw me for a loop

I attempted to populate a web SQL database with some data, but encountered an issue. Here is my code: database(); for(var i=0; i<m.length; i++){ showid = m[i].id; showtitle = m[i].title; insert(); } function database(){ //open the database ...

What is the best way to distribute multiple inline-block elements evenly?

Is it feasible to evenly distribute numerous elements in a div with adjustable width? Check out this example that doesn't work. While using text-align:center; will center the elements, margin:0 auto; does not have any effect. I am aiming for somethin ...

Is it possible to create a component with a button that triggers the rendering of a different component?

I am struggling to implement an 'edit' button within a component that, upon clicking, should display a separate component known as a 'client edit modal'. I'm facing challenges in figuring out how to achieve this functionality. The ...

Jquery does not display the variable in the Firefox console using console.log

I am trying to retrieve the data value from the text input, but it's not getting logged in the console. I even tried using a breakpoint, but it still doesn't console anything. What could be the issue? var x = '' $(() => { $("#en ...

Issue with displaying Bootstrap Modal in fullscreen mode

Utilizing Bootstrap Modal for quick news pop-ups has been a challenge. Currently, the issue is that when clicking on a link, it only displays a small box instead of fullscreen. My question simply put: Is there a way to append the width and height propert ...

Retrieve the data contained within a displayed embed tag that includes a src attribute

Can anyone provide guidance on how to retrieve the content of an embed tag using src attribute? I have an embed tag pointing to a custom page as src. I tried to use jquery to access the rendered content but I am not getting anything back. Any suggestions ...

Unexpected behavior of Bootstrap columns within nested rows, occurring between the small and extra-small breakpoints

Currently, I am in the process of developing a small website using Bootstrap 5. My goal is to have 6 elements displayed on two lines for breakpoints greater than or equal to md and on a single line for smaller breakpoints. It all seems to be working fine f ...

Automatically update the version of the appcache manifest file

After enabling application cache for my web application, I want to ensure that the cache manifest file's version is automatically updated every time I generate the war or deploy the application. This will ensure that the browser fetches content from t ...

The alignment issue persists in HTML/CSS despite troubleshooting efforts

I am facing a challenge while attempting to center text within a modal window, despite my efforts the text remains uncentered. This is my HTML code: <div ng-init="modalCompassDir()"> <div class="myModal"> <img class='floor ...

Attempting to utilize PFUser within a NodeJS environment

I have been utilizing the PFUser class to generate user accounts for individuals using an iOS application to access a Parse-Server. Now, I am looking to transition this user management functionality from an iOS app to a web app (specifically NodeJS). Init ...

Using PHP to dynamically change the title of a Bootstrap modal

I've been attempting to dynamically update the title of my modal using PHP. The title I wish to display is stored in a variable and is being reassigned based on user input. Below is my PHP code snippet: $studentName = $results['Studentname&apo ...

Dealing with Issues of HTML and CSS Positioning

Why are my buttons not maintaining their positions correctly when the window is resized? I thought it should work as intended. In my previous inquiry, I was able to successfully position elements for window resizing (CSS Top Relative To Screen). However, ...