Can the top header stay fixed to the top of the screen even when scrolling down?

Code snippet: http://jsfiddle.net/R3G2K/1/

In my project, there are multiple divs with content and each div has a header. My goal is to make the last header that goes out of viewport "sticky" or fixed at the top.

I have explored various solutions for this issue, but none of them seem to be effective when dealing with multiple headers.


$('.content').scroll(function(){
    console.log('scrolling')
    $('.itemheader').each(function(){
        var top = $(this).offset().top;
        console.log(top);

        if(top<25){
            $(this).addClass('stick');
        } else {
            $(this).removeClass('stick');
        }
    })
});

I suspect the problem lies in the fact that each header shares the same class name without a unique identifier, causing my previous attempt to fail.

Answer №1

Discover the perfect solution at this link

This resource provided exactly what I needed:

Check out the demo here

$(document).ready(function () {
// 1. Accessing necessary variables
var $container = $('#box');
var $headers = $container.find('h2');
var zIndex = 2;
var containerTop = $container.offset().top + parseInt($container.css('marginTop')) + parseInt($container.css('borderTopWidth'));
var $fakeHeader = $headers.filter(':first').clone();

// 2. Positioning h2 elements absolutely and increasing z-index
$headers.each(function () {
   // set position absolute, etc
   var $header = $(this), height = $header.outerHeight(), width = $header.outerWidth();

   zIndex += 2;

   $header.css({
       position: 'absolute',
       width: $header.width(),
       zIndex: zIndex
   });

   // create white space
   var $spacer = $header.after('<div />').next();
   $spacer.css({
       height: height,
       width: width
   });
});

// 3. Attaching scroll event to change text of fake heading
$container.scroll(function () {
    $headers.each(function () {
        var $header = $(this);
        var top = $header.offset().top;

        if (top < containerTop) {
            $fakeHeader.text($header.text());
            $fakeHeader.css('zIndex', parseInt($header.css('zIndex'))+1);
        }
    });
});

// 4. Initialization steps
$container.wrap('<div class="box" />');
$fakeHeader.css({ zIndex: 1, position: 'absolute', width: $headers.filter(':first').width() });
$container.before($fakeHeader.text($headers.filter(':first').text()));

});

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

Ensuring the server application is up and running before initiating the mocha tests

This is similar to Ensuring Express App is running before each Mocha Test , but the proposed solution isn't effective + I am utilizing a websocket server In essence, I'm making use of a websocket framework called socketcluster and this represent ...

Engaging with the CSS content attribute

Below is a code snippet that inserts an image before the header tag. Is there a way to incorporate JavaScript or jQuery in order to execute certain actions when the inserted image is clicked? h1::before { content: url(smiley.gif); } The HTML code fo ...

Utilize anychart.js to define the axis using JSON data

I'm relatively new to using anychart js and encountering some obstacles. I have a json file that is being fetched from an API, containing data on NBA players' statistics. You can find the json file here: My goal is to display the date data on th ...

When the video message bubble is touched within the chat app, a video player will automatically pop up (using React Native)

Currently, I am developing a chat app in React Native that can handle the sending and receiving of video files. However, I am facing challenges with activating the video player when a user presses on the video message inside the chat bubble. Despite my att ...

Moving data from the bottom of the page to the top

I am facing a situation where I have several foreach loops on a page that calculate the sum of variables. By the end of these loops, a specific variable contains data. However, I now need to display this data at the top of my page before the foreach loop. ...

Encountered an error in React where the declaration file for a module could not be located

New to Typescript and trying to incorporate a splitter into my project. I'm utilizing SplitPane from "react-split-pane/lib/SplitPane" and Pane from "react-split-pane/lib/Pane" in my Typescript project, but encountering an error: Could not find a de ...

Utilizing Socket IO and Node JS to stream audio from a microphone via sockets

I am currently developing an app that requires users to use their phone's microphone to communicate with each other in the game lobby. However, I have encountered several challenges along the way. My approach involves using Node JS socket io and sock ...

Disregard the instructions upon loading the page

I've implemented a directive to automatically focus on the newest input field added to my page. It works well, but there is one issue - when the page loads, the last input is selected by default. I want to exclude this behavior during page load and in ...

Synchronizing other components with a filtered query from the List in Admin-on-rest: Best practices

I am looking to incorporate the following structure into my page: 1. Cards displaying summaries (revenue, users, etc.) 2. Google Maps integration 3. List element Within the List element, there is filtering involved. I am struggling with how to utili ...

Utilizing HTML snippets for AJAX integration

Let's dive in, I may be completely off track here. I am currently working with Wordpress. On a page I am creating an HTML select menu (Main Menu) with options that correspond to each page on the site. This menu is visible on the page. In addition, ...

When adding an object to an array in AngularJS, it seems to trigger updates for

Currently, I am fetching data from a WebAPI and then storing it in an array called products, which is scoped. $scope.products In addition to the products array, I also have another scoped array named selectedFish. $scope.selectedFish = []; My objective ...

How is it possible for the igx-expansion-panel to close when there is a nested angular accordion present?

Currently, I am faced with the challenge of closing the igx-expansion-panel within my Angular project. While everything functions smoothly with a standard panel, things get a bit tricky when dealing with nested angular accordion structures using igx-accord ...

Is there a way to raise an error in React Native and make it visible?

I am working on a functional component where I need to call a method from another .js file. The method in the external file intentionally throws an error for testing purposes, but I want to propagate this error up to the functional component's method. ...

Having Trouble Operating Virtual Tour in Flash

I recently used a third-party software to create a virtual tour for my client's website. The virtual tour works perfectly fine on its own, as you can see here: However, when I tried to include the virtual_tour.html page on the index page of the websi ...

How to save the value of `this.$route.params.id` in a Vue.js data property?

I am currently working with Vue.js 3 and have a sample code for routing and passing parameters. Below is the Home.vue page: <template>   <div class="home">     <h1>       All Destinations     </h1>     < ...

Utilize Meteor-tabular to effortlessly export data with convenient HTML5 export buttons

Currently, I am utilizing the tabular package to display data from a collection in a table format. However, when attempting to export the data using html5 export buttons with the button (csvhtml5), only the length of data visible in the table is exported, ...

Utilizing the Context Object in a Slack API Bolt Project for seamless property transfer between methods

I'm currently working on a Slack app using the JavaScript Bolt framework. This app essentially listens for specific message keywords in channels and then forwards those messages to the users of the app. My main goal is to add a permalink to the forwa ...

Combining Jquery and PHP to Implement Date Type in MySQL Database

I am looking for a way to save user birthdates in MySQL as a date type on my website. The data I receive includes: Day - e.g. 1 or 11, 23, etc. Month - e.g. March, April, December Year - e.g. 1975, 1964, 1944, etc. For example: 3 March 1966 How can I c ...

Creating a cron job that can be rescheduled using Node.js

I am utilizing the node-schedule package from GitHub to create cron jobs. While I have successfully created a basic scheduler, my goal is to make it reschedulable. Within my application, users can initiate tasks for specific dates. This can be easily achi ...

Swapping icons in a foreach loop with Bootstrap 4: What's the most effective approach?

I need a way to switch the icons fa fa-plus with fa fa-minus individually while using collapse in my code, without having all of the icons toggle at once within a foreach loop. Check out a demonstration of my code below: <link rel="stylesheet" href= ...