Fixed bar on top, revealed only when the scroll attempts to conceal it

I have placed a menu on the top section of my website, but not at the very top. I would like it to stick to the top of the page when the user scrolls down and disappears from view. However, if the title is still visible, I want the menu to remain below it in a seemingly fixed position.

Is it possible to achieve this effect using only CSS without JavaScript? I remember seeing it on a website before, but I can't recall where exactly.

Thank you in advance (and please excuse my imperfect English!) ;)

Answer №1

Here is the solution you've been searching for: https://jsfiddle.net/QuVkV/2/

This is the HTML structure:

<div id='wrapper'>
    <div id='upper'>This is upper content</div>
    <div id='position-saver'>
        <div id='bar'>This is the menu bar</div>
    </div>
    <div id='lower'>This is some content lower than the menu bar</div>
</div>

Below is the CSS:

#wrapper {
    width: 100%;
    height: 2000px;
}

#upper {
    width: 100%;
    height: 100px;
}

#position-saver {
    height: 50px;
    width: 100%;
}

#bar {    
    position: static;
    height : 50px;
    width: 100%;
}

And here's the JavaScript:

$(document).on('scroll', function(){
    if ($('#bar')[0].offsetTop < $(document).scrollTop()){
        $("#bar").css({position: "fixed", top:0});            
    }
    if ($(document).scrollTop() < $("#position-saver")[0].offsetTop){
        $("#bar").css({position: "static", top: 0});           
    }            
});

Answer №2

I've come across this type of design on various websites, including 9gag.com.

One way to achieve this is by utilizing the position property in css.

You can check out an example here: JSFiddle

#scroll-me{ 
    width:100%;
     height:100px; 
     background:#333;
     position: fixed;
     top:15px;
     }

By setting position:fixed and top:15px for the scroll-me div, it will always stay 15px from the top.

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

Upon concatenation, the screen automatically returns to the beginning of the page

I've set up a page with a list of items, and at the bottom there's a handy "Load more" button that fetches new items to add on top of the existing list: handleLoadProducts = (append = false) => { this.setState({ isLoading: true, ...

What is the method for retrieving this data using Javascript?

I received this JSON-encoded data: { "error": { "msg":"Concurrent verifications to the same number are not allowed", "code":10 } } and I tried to access the 'msg' value using JavaScript as follows: $("#buttonPhoneSubmit ...

Struggling with jquery's addClass method when trying to apply a class to

Below is a sample tr: <tr> <td><input type="text" class="ingredient required" name="ingredient"></td> <td><input type="number" class="amount required" name="amount" ></td> <td><input type="number" c ...

Issues encountered with Nextjs 13.4 and Next-Auth 4.2 regarding the signIn("credentials", { }); functionality not functioning as expected

When using next-auth credentials in my current project, I encountered an issue with the signIn() function from next-auth/react. It appears that the redirection to the admin page persists regardless of whether the login details are correct or not. {error: n ...

Checkbox remains selected even after navigating back

I am currently working on a code that involves using checkboxes. When I click on them, the checkbox value is appended to the URL with a hash. However, when I go back or press the back button, the URL changes but the checkboxes remain checked. Below is the ...

What would be the best approach to convert this jQuery code into a more structured object-oriented programming format

Recently, I began working on my first major front-end heavy website. My goal was to create a unique content management system-driven single-page website with over 100 internal pages. The URL would remain constant, but whenever a user clicked on any link b ...

Strange Behavior When Floating Right in Chrome

There's a strange issue that I'm facing, only in Chrome. It seems to be adding some extra space on top of an element with float: right, but only when the browser window is resized (you can see how the name then shifts under the header): This pro ...

Steps for deactivating AMD on four files and sequentially loading them using webpack

I am facing an issue where I need to disable AMD on 4 files and ensure that video.js is loaded before the other 3 files, as they are dependent on it. My attempt to achieve this in webpack.config.js was unsuccessful: const path = require('path') ...

Is there a way to extract video frames from a WebRTC local stream and transfer them to Python?

I am in the process of developing a video call application similar to Google Meet or Zoom, incorporating object detection using Python Flask or Django. Here is how the application functions: Users can join a channel for the video call The camera ini ...

Adjusting Bootstrap buttons to have a margin-left of -1px when clicked outside the designated area

I utilized Bootstrap in my project, implementing the following code: <div class="input-group"> <input type="text" class="form-control input-lg" autofocus> <span class="input-group-btn"> <button class="btn btn-primary btn-lg" t ...

The rules for prioritizing CSS selectors

Struggling with CSS selector rules and specificity? I've already checked this for specifics. Even tried using firebug and inspecting elements in Chrome to copy the CSS path, but still can't get it to work. This is my first time creating a website ...

How do I retrieve the content within this HTML element using JavaScript based on its ID?

Is there a way to extract the string from this specific HTML element using JavaScript? The element has an id of recItemString_GPLA\|input, and within it, there is a string containing "qty" that I need to retrieve. Upon inspection of the element, the f ...

Firebase 9 - Creating a New Document Reference

Hey everyone, I need some help converting this code to modular firebase 9: fb8: const userRef = db.collection('Users').doc(); to fb9: const userRef = doc(db, 'Users'); But when I try to do that, I keep getting this error message: Fir ...

Speedy Guide to Referencing Variables in JavaScript

I'm hoping for some clarification on this topic. Let's imagine I have 2 global variables: var myarray=[1,3,5,7,9],hold; and then I execute the following code: function setup() { alert (myarray[0]);//displays 1 hold=myarray; alert (hold);//seem ...

Yeoman webapp error: Issue with incorrect CSS path in subfolder

I have been using the yeoman webapp generator (0.5.0) and my app directory is structured like this: app/ ├── dir1 │ └── index.html ├── favicon.ico ├── images ├── index.html ├── robots.txt ├── scripts │ └ ...

The robots.txt file in Nuxt.js allows for multiple disallow directives for each user agent

With the Nuxt module called nuxt-robots, how can I set up multiple disallow rules per user agent? Currently, my configuration looks like this: robots: () => { return { UserAgent: '*', Disallow: '/search/', Si ...

Error in IONIC 3: The code is unable to read the 'nativeElement' property due to an undefined value, resulting in a TypeError

I am currently learning about IONIC 3 and working on an app that utilizes the Google Maps API. However, when I try to launch my app, I encounter the following error message: inicio.html Error: Uncaught (in promise): TypeError: Cannot read property ' ...

The issue persists with Angular's overflow hidden not functioning properly, and similarly, the show password button is

I created a login page using Angular Material, but I'm facing some issues. The problem is that when I set the style overflow: hidden, the show password button stops working. Additionally, if I click the button twice, the webpage refreshes, which shoul ...

Issue: The module could not be located within the project or in any of the directories, including node_modules

Error: It seems we're having trouble resolving the module navigation/stack-routes from MainTabs.tsx file in gymzoo project directory. The path navigation/stack-routes could not be located within the project or node_modules directory. Greetings! I&apo ...

Angular Digest Loop for Dynamic Photo Grid Styling

I have a special filter that alters the objects being filtered. However, when I apply ng-style="item.gridSize", it triggers my custom grid algorithm. This algorithm was adapted for my requirements from a source found at this link. angular.module("custom.m ...