Div with Sticky Header and Scrolling Ability

I am working on a project that involves creating a scrollable div with "title" elements inside. I want the title element of each section to stick to the top of the div as I scroll, similar to how a menu sticks to the top of a webpage. An example of this can be seen in the Mac OS X calendar's "Day" view.

I have found a solution for making the element stick, but I need help figuring out how to detect when a title element reaches the top of the scrollable div.

Here is the scenario:

<div class="container">
    <div class="floatLeft">
        <div class="scrollingDiv" style="height:100px; overflow-y:scroll; overflow-x:hidden;">
            <ul>
                <li>
                    <div>
                        <h4>Title</h4>
                        <div>Content</div>
                    </div>
                </li>
                <li>
                    <div>
                        <h4>Title</h4>
                        <div>Content</div>
                    </div>
                </li>
            </ul>
        </div>
    </div>
    <div class="floatRight"></div>
</div>

Is there a way to determine when the second "Title" reaches the top of the "scrollingDiv", not the top of the entire page?

Any assistance would be greatly appreciated!

Answer №1

To achieve a sticky element, you can set its top property to zero and apply position:absolute; using CSS.

.stickyTop {
    position:absolute;
    top:0px;
}

This will keep the element fixed at the top of the page at all times.

If you want to determine when an element has reached the top of the window, you can use offset() to track its current position and check if it's close to the top.

$('div.scrollingDiv').scroll(function() {
    var active = null;
    $('.scrollingDiv h4').each(function(idx, val) {
        var topOffset = $(val).offset().top;
        if (topOffset < 20) // elem is 20 px from top
        {
            // Element closest to the top
            active = $(val);
        }

        console.log(active); // Element nearest to the top
    });

});

The code above iterates through all the h4 elements to find the one closest to the top of the page, then logs it.

You can combine these techniques to create something unique like a Creative jsFiddle.

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

The function ng-click does not successfully uncheck ion-radio

In the process of developing my application using the ionic framework, I encountered a challenge where I needed to deselect an ion-radio button when clicking on an input tag. Despite attempting to achieve this functionality through this ionic play link, I ...

What is the method to retrieve the selected value from a drop-down menu that is connected to JSON keys?

I am just starting to learn AngularJS and I need help with binding column names (keys from key-value pairs) to a select list. I want to be able to retrieve the key name when the selection in the select list is changed. The select list displays: name, snip ...

Why does the jQuery .each loop only loop when I console.log?

Feeling a little confused right now. I have a .each function that successfully displays all results from JSON when I use console.log, but for some reason, when I try to output using .html(), it only shows one result at a time. Any idea why this might be ha ...

Is JSON formatting essential for Highcharts? How to divide and preprocess data for creating charts?

Seeking assistance with extracting data from a JSON at the following link: I am attempting to integrate this data into highcharts for visualization. Although I have a functioning chart, I am struggling with properly formatting the JSON mentioned above du ...

Utilize MySQL to populate highcharts with data

Learning the ropes of web programming, I have a personal project to monitor expenses. Simply put, my database stores data on total expenditures for this month and last month. I am able to display it manually (via echo), but I'm struggling to pass the ...

Issues with Nuxtjs routing on Netlify

I currently have a NuxtJs (Vue) application deployed on Netlify. The issue I am facing is that when I redirect to other pages, the URL ends up concatenating the last page and the next page. For example, if the current page URL is https://page-example/regi ...

Creating a JSON object hashtable using jsHashtable: A step-by-step guide

I have a good understanding of how to create a hashtable from scratch using jshashtable. For instance: <script type="text/javascript" src="jshashtable.js"></script> <script type="text/javascript"> var typesHash = new Hashtable(); ...

What is the reason for npm and yarn to download multiple versions of jquery?

For the purpose of investigating how package managers like npm, yarn, and cnpm work in Node.js, I conducted an experiment. During the test, I came across two packages: jquery-dreamstream and jquery.tree. Both of them have a dependency solely on jquery wit ...

Having Trouble with Jquery UI Autocomplete and JSON Integration

Hi everyone, I'm currently investigating why the autocomplete() method is not performing a GET request when I append a variable to the end of the source URL. Here's an example: <script> $(document).ready(function(){ var se ...

Resetting the quiz by utilizing the reset button

Hello everyone, I'm new to this platform called Stack Overflow. I need some help with my quiz reset button. It doesn't seem to be working as intended. According to my code, when the reset button is clicked at the end of the quiz, it should bring ...

The CSS specificity of a nested HTML element with no explicitly defined styles

Seeking clarification on this specific CSS cascading/inheritance rule. In the given example, I would have expected the text inside the em tag to be colored #000000, but I was informed that it would actually be colored #ff0000. I am familiar with CSS speci ...

The sorting of elements using the jQuery sort() function encounters issues on webkit browsers

Looking for a solution to sort elements by a number? Consider this part of a function that does just that. The number used for sorting is fetched from a data-ranking attribute of the element: $(".tab_entry").sort(function(a,b){ return parseFloat(a.dat ...

Creating Tailored Breakpoints with Bootstrap for a Unique Design

Currently, I am delving into the world of front-end web design and taking advantage of Bootstrap for creating a responsive layout. However, I have noticed that Bootstrap only offers 5 predefined breakpoints. I am curious to know if there is a way to cust ...

Combining the results of JavaScript comparisons into a unified object array and adding a new value if it matches an existing value within the same

I am interested in consolidating the array to represent the base folder hierarchy. In the array provided, "Level 1" is the lowest level with no children folders. The "other level" contains various folders all under the "Top Level." The array structure is ...

Does JavaScript automatically round large numbers?

I have a simple array: myArray = [{"egn":79090114464},{"egn":92122244001},{"egn":10005870397643185154},{"egn":10000330397652279629},{"egn":10000330397652279660},] However, when I append the values from thi ...

How to retrieve the data variable in Vue JS script

I recently started using vue.js and I'm working with version 2.5.13. In my component file script, I am trying to access a data variable but it keeps returning as undefined. The id attribute in the component is displaying the correct value, however w ...

Is it possible to use uglifyjs to merge multiple files into a single minified file?

I attempted to compress multiple javascript files into one using the uglifyjs tool, but encountered an issue. I ran $node uglifyjs.js to execute the file. Below is the content of the uglify.js file: var fs = require('fs'); var uglifyjs = re ...

The Highcharts datetime line takes a detour through time when faced with unorganized data

Despite my best efforts to obtain sorted data from various API calls, I find myself with unsorted data that needs to be plotted in a timeseries graph. { xAxis: { type: 'datetime' }, series: [{ data: [ [Date ...

In Javascript, the splice method removes all elements except the specified element

I've got a straightforward script here that grabs content from an input box, converts it into an array, deletes a specific element, and then displays the remaining text. My issue is with using "splice()" to remove the item as it's deleting every ...

Setting up a Webpack configuration to compile modules within the node_modules directory

My webpack and babel configuration is causing some issues. I installed my component repository (es6 module without webpack configuration) as a node_module, but it's not working - I'm getting an 'Unexpected token import' error because Ba ...