Adjusting the position of a stationary element when the page is unresponsive and scrolling

Managing a large web page with extensive JavaScript functionality can be challenging, especially when dealing with fixed position elements that update based on user scroll behavior. A common issue that arises is the noticeable jumping of these elements when scrolling quickly or using the mouse wheel due to delays in executing code related to the scroll event.

To illustrate this issue, you can check out this jsfiddle example: http://jsfiddle.net/jorsgj2b/1/. In this demo, the delay in function execution is simulated using setTimeout.

<div class="header"></div>
<div class="main"></div>
<div class="float"></div>

.header {
    width: 100%;
    height: 200px;
    background-color: #787878;
}

.main {
    width: 100%;
    height: 1400px;
    background-color: lightblue;
}

.float {
    position: fixed;
    width: 100px;
    height: 50px;
    top: 233px;
    right: 25px;
    background-color: red;
    z-index: 2;
}
$(function() {
    $(window).scroll(function() {
        setTimeout(updateFloat, 50);        
    });
});

var updateFloat = function() {
    var mainTop = $('.main').offset().top;
    var scrollPos = $(window).scrollTop();
    var floatOffset = 25;
    var newTop = (scrollPos > mainTop) 
        ? floatOffset + 'px' 
        : mainTop + floatOffset - scrollPos + 'px';

    $('.float').css('top', newTop);;
}

Dealing with this issue can be tricky. Some attempted solutions include updating margins instead of top positions and switching between absolute and fixed positioning. Utilizing CSS transitions could potentially offer a workaround, but implementation may vary depending on the specific scenario.

Answer №1

To enhance the stickiness of an element, consider adding position: sticky to your CSS for browsers that support it (currently only Firefox and Safari as per caniuse.com).

In order to reduce delay in scroll events, optimize the updateFloat() function by caching values instead of repeatedly looking them up. Here's an example:

var mainElement = $('.main');
var windowElement = $(window);
var floatElement = $('.float');

var updateFloat = function() {
    var mainTop = mainElement.offset().top;
    var scrollPos = windowElement.scrollTop();
    var floatOffset = 25;
    var newTop = (scrollPos > mainTop) 
        ? floatOffset + 'px' 
        : mainTop + floatOffset - scrollPos + 'px';

    floatElement.css('top', newTop);
} 

If rendering issues arise due to layering with other elements, separate the ".float" element into its own render layer for faster GPU compositing. This can be achieved by applying styles such as transform: translateZ(0); or utilizing the will-change property. Update your CSS accordingly:

.float {
    will-change: scroll-position;
    transform: translateZ(0);
    position: fixed;
    width: 100px;
    height: 50px;
    top: 233px;
    right: 25px;
    background-color: red;
    z-index: 2;
}

Exercise caution when adding render layers as it may increase memory usage and affect features like text anti-aliasing.

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

Understanding the AJAX FormData Object

Recently, I've been experimenting with using the ajax FormData object to handle multipart/form-data. However, I'm encountering a bit of confusion - specifically regarding the use of [0]. Can anyone shed some light on what that signifies? Here&ap ...

What could be causing my webpage content to be partially hidden by my CSS menu?

I am currently working on my website which features a CSS menu with my website logo, a text box, and a dropdown. Additionally, I have created a login form using a table like the one shown below. <p>&nbsp;</p><table width="40%" border="0 ...

Looking to automate the selection of a dropdown menu using Selenium with JavaScript

Below is the code snippet for a drop-down: <div class="w-1/2 px-8 pt-6"> <div class="Styled__FieldWrapper-sc-1fqfnqk-1 bQZNMa mb-6"> <label class="form-label" for="transfer.account">Transfer Acc ...

anchor to # inquiry

I'm curious about the href link and its usage, I tried looking it up online but didn't find much information. Here is an example of a href link I have: <a href='#' onclick='openSerialWindow();return false;'><h:output ...

Including hyperlink tags within a CSS file

Can you create internal links within a CSS file, like inserting a table of contents at the top where you can click on an item and immediately jump to that section in the CSS file similar to an anchor tag? This feature would be extremely handy for long CSS ...

Transform your image using a stunning zoom-in effect

Currently, I am experimenting with a feature for my website where I want images to switch upon hover. While I have successfully achieved the image switch on hover, I am looking to create smooth transitions between the switches, with the second image being ...

Trouble displaying Bar Graph in chart.js using PHP

I am facing a challenge with creating a bar graph using chart.js that loads data from a PHP array via ajax. The data is successfully loaded through ajax, as confirmed in the console, but I am unable to display it on the graph. Here's what I see in the ...

What is the best way to conceal a Boostrap Navbar using jQuery?

Attempting to create a hidden side navbar using Jquery and Bootstrap 4. Struggling with the .on('click', ...) event handler for a button not hiding the sidebar as expected despite all files loading correctly according to the developer tools. Atte ...

Determine if a MySQL query in node.js returns no results

I'm trying to determine if there are no matching results in MySQL using Node.js. How can I achieve this? mysql.query("select * from table1 where name = 'abcd'", function(error, result, field) { if(error) { handleNoError(error); ...

Discovering the property name of an object in Angular using $watch

Is there a way to monitor an object for changes in any of its properties, and retrieve the name of the property that changed (excluding newValue and oldValue)? Can this be accomplished? ...

The importance of displaying doughnut chart tooltips in Angular 5 console

Is there a way to consistently display tooltips for a doughnut chart? This code snippet might help: Chart.pluginService.register({ beforeRender: function(chart) { if (chart.config.options.showAllTooltips) { // create an array of tooltips // we ...

What is the best way to utilize regex for replacing a string within Node.js environment?

I'm struggling with updating the string in my code. Essentially, I have a .php file and I want to modify some constants using the replace package. The output of my current code is: // Current Output define('DB_NAME', 'foo'); // ...

Issue with Django: Unable to fetch data from server response in Ajax

Just starting out with Django and trying to figure out how I can dynamically add content from a python script without reloading the page. In my views.py file, I have two functions - one for uploading a file (home) and another for calling a python script t ...

Teaching sessions along with the implementation of functions

I've created a set of input fields with the class replaceInput. The idea is to have a simple function that clears the value when the user focuses on the field, and then returns it to 'X' if the field is empty on focus out. My query is, coul ...

Only the first Yii ajax jQuery request is successful when multiple requests are made

There seems to be an issue with my input field and button pairs for ajax requests. The functionality works fine the first time, but after that initial request-response cycle, the other buttons don't trigger the ajax function. I have a data grid list ...

Determine the quantity of items that meet specific criteria

The initial state of my store is set as follows: let initialState = { items: [], itemsCount: 0, completedCount: 0 }; Whenever I dispatch an action with the type ADD_ITEM, a new item gets added to the items array while also incrementing the count in ...

What happens if I attempt to pass a blank field in multer?

I am trying to verify if the image field passed to Multer will include the file. There are no errors being thrown by Multer and the server is currently processing the request. ...

Using Middleware to Access LocaleStorage in Universal Mode

Here's the dilemma: My understanding is that accessing LocaleStorage from Middleware in Universal mode is currently not possible (at least not out-of-the-box.) Question: Is there any way to solve this issue? Are there any modules or solutio ...

Ways to resolve the error message "Type 'Promise<{}>' is missing certain properties from type 'Observable<any>'" in Angular

Check out this code snippet: const reportModules = [ { url: '', params: { to: format(TODAY, DATE_FORMAT).toString(), from: format(TODAY, DATE_FORMAT).toString() } }, { url: 'application1', params: { to: for ...

The <span> tag creating a surprise gap following a word

Using Angular4, I've come across an odd issue where one of my span elements is adding an extra space to the end of words like this: https://i.stack.imgur.com/H4TD7.png The only CSS properties that are set include font-family, -webkit-font-smoothing, ...