Scrolling through content can reveal multiple sticky elements that remain aff

I have header and sidebar div blocks and I need them to stick at the top once the scroll event is triggered due to our specific requirements.

While making a single element sticky is not a problem, having more than one causes issues with scroll action and causes it to jump back to the top.

Is there a clean solution to this problem without relying on plugins?

Take a look at my JS Fiddle for reference.

Below is the script that works well for a single element:

$(window).on("scroll", function () {
    var fromTop = $(window).scrollTop();
    $(".sidebar").toggleClass("fixed", (fromTop > 50));
    $(".header").toggleClass("fixed", (fromTop > 50));
});

Answer №1

Check out this similar solution:

$(window).on('scroll', function () {

    var windowTop = $(window).scrollTop();
    var elementTop = $('.anchor').offset().top;

    if(windowTop > elementTop) {
        $(".sidebar").addClass("fixed");
        $(".header").addClass("fixed");
    } else {
        $(".sidebar").removeClass("fixed");
        $(".header").removeClass("fixed");
    }

});

JS Fiddle

Answer №2

If you're looking for a straightforward solution using only HTML and CSS, you can achieve the desired effect by simply adding the following style:

position: fixed;

This will ensure that both div containers remain fixed in place regardless of the user's scrolling behavior. You can view the solution in action here: http://jsfiddle.net/N4maR/3/

There doesn't seem to be a compelling reason to have the containers switch to a fixed position after a specific scrolling threshold, so keeping them fixed from the start may be the best approach.

Answer №3

It's surprising how there are only a few responses to this question.

When dealing with two sticky items that need to remain separate within different wrappers, a key strategy is to apply top: 50px to the second sticky item (or the equivalent height of the first) to ensure it remains 'stuck' in place without overlapping the first item.

Furthermore, there are numerous factors that can cause sticky positioning to not work as intended. For a comprehensive overview of possible scenarios, refer to this thread.

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

Using Jquery to access items in an array with associative keys

I'm attempting to arrange my list of locations based on shortest to longest distance using the following code snippet: for(var i=0; i<locations.length;i++) { var swapped = false; for(var j=locations.length; j>i+1;j--) { if ...

Tips for integrating CSS3 into Android WebView

Currently, I am working on an Android application that utilizes HTML5. My goal is to implement element rotation using CSS3 transformations. However, I need to ensure that the app remains compatible with Android 2.3. What would be the most effective metho ...

Handle all link clicks on the webpage

My challenge is that some users are required to utilize a virtual desktop in order to access specific information on my website. However, within the virtual environment, there are links leading to external content that do not function properly. I am seekin ...

Chrome browser exhibits a phenomenon where the Bootstrap modal will erroneously print the same page multiple times based on the

When I open a modal, there's a print button inside it. I've researched solutions provided here and here to enable printing of Bootstrap modals, but I'm encountering a Chrome-specific bug. The issue doesn't occur in Safari, Firefox, or E ...

Immediate display of collapsed/toggle menu in a Bootstrap navbar

I have created a bootstrap responsive navigation menu that collapses into a box when the page is resized. It's a standard menu with bootstrap, but I'm facing an issue where the menu automatically appears when the page gets small instead of needin ...

issue with transmitting PHP data through ajax causing data to be undefined

This function is responsible for calling and changing the values <select width="100" name="produto" id="produto-list" class="produtoInputBox" onChange="getapolice(this.value);" <?php echo $permissao; ?> > Here's the function in actio ...

Leverage asp.net AJAX capabilities using JavaScript

I have a question that may seem basic. I am using ASP.NET ajax toolkit and jQuery. Is it possible for me to call a server-side method/function from JavaScript in order to update a control? Client-side send_request(foobar, args); Server-side private voi ...

display the hidden box contents when clicking the button within a PHP loop

I am attempting to create a simple e-commerce site for learning purposes, but I encountered an issue when trying to display information upon clicking a button. The button does not seem to trigger any action as expected. It is meant to reveal text from the ...

CSS Switchable Style Feature

I am in need of some assistance with the navigation on my website. You can find the current code at this link: http://jsfiddle.net/Sharon_J/cf2bm0vs/ Currently, when you click on the 'Plus' sign, the submenus under that category are displayed bu ...

Can you explain the concept of ".el" as it relates to JavaScript, HTML, and jQuery?

After conducting a search on Google, I didn't find much information. Perhaps I am using the wrong terms. I am trying to figure out what the "el" in "$.el" represents in the following code snippet: $.el.table( $.el.tr( $.el.th('first name ...

CSS - Text and dropdown misalignment due to spacing issue

I'm looking to decrease the spacing between the text "Allow type of Compartment Option" and the dropdown box. Here is the code snippet being used: .cl-checkbox { padding-left: 20px; padding-bottom: 10px; padding-top: 20px; ...

The issue of batch-wise data clustering on Google Maps when zooming in or out

//The code snippet provided below initializes a map with specified settings and clusters markers based on the data sent in patches of 10000.// var mapDiv = document.getElementById('newmap'); map = new google.maps.Map(mapDiv, { center ...

JavaScript - Implementing dependency injection with promises

I am facing a challenge in passing an object around in JavaScript, with some jQuery involved. :) My goal is to execute the FlappyBarHelper.getUserPropertyCount() method once the promise.success function has completed. I attempted to pass this.FlappyBarHel ...

Ways to eliminate dates from the text of listed items

Before finalizing their registration, users on our site are shown a review page. This panel displays all the items they have selected, creating a unique and variable list for each individual. However, each item in the list starts with a distracting date/ti ...

What is the best way to randomly display an image from a JavaScript array within an HTML document?

I currently have this code in my HTML and JavaScript files, but I am having trouble with displaying images without using a URL in the JavaScript file. The images are located in my project folder. However, when I open the HTML file, the images do not appear ...

Attr() is not displaying the desired information

I'm encountering an issue with the attr() function not working as expected. Despite seeing the correct tag with the attribute in the sources, the tag is being created but it's not visible on the website. app.html('<h1>' + product ...

Obtain the corresponding element from the selectors utilized in the jquery.is function

$("#see1, #seeAlso1, .see").is(':checked') This code snippet will give you a boolean result. Are you looking for a way to retrieve the first element that matches and returns 'true'? ...

Determine the dynamic height of content in a TypeScript file

Could you please provide guidance on obtaining the height of the content within this particular div element? For example, I need to calculate the dynamic height of the content. https://i.sstatic.net/2kNk3.png code .html <div class="margin-top-4 ...

Angular error Uncaught ReferenceError: jQuery is not found

https://i.sstatic.net/RLZXY.png I included several JavaScript files in my component, but upon starting the app, the browser displays an error message: Uncaught ReferenceError: jQuery is not defined. I made sure to load jQuery before any other files, so I& ...

Utilizing slid.bs.carousel to retrieve values upon slide change

I am working on incorporating Bootstrap 4's Carousel with jQuery and PHP to create an odometer that dynamically changes its value on each slide. My plan is to utilize .addClass based on the length of the value. One challenge I am facing is that when ...