I would like to create a div, that is situated beneath a block of content but that once the page has been scrolled enough to contact its top boundary, becomes fixed in place and scrolls with the page.
-
6As of June 2014, the [Sticky-kit jQuery plugin](http://leafo.net/sticky-kit/) is one of the easiest options, providing an extremely low barrier to entry and lots of features. Great place to start if you're looking for an easy way to get off the ground quickly. – user456584 Jun 21 '14 at 00:46
-
2CSS tricks: http://css-tricks.com/scroll-fix-content/ – Ciro Santilli OurBigBook.com Dec 22 '14 at 11:35
-
60Adding CSS `position: sticky; top:0;` works in most browsers in January 2017. – Colin 't Hart Jan 23 '17 at 13:35
-
25Holy crap, that `position: sticky;` thing is magical. – tscizzle Jun 30 '17 at 03:22
-
it can be because of display flex, read this : https://stackoverflow.com/a/66966273/5361964 – Zohab Ali Apr 06 '21 at 09:46
-
`position: sticky; top:0;` in a `relative` container works for me. – Marzieh Mousavi Feb 19 '22 at 11:44
24 Answers
You could use simply css, positioning your element as fixed:
.fixedElement {
background-color: #c0c0c0;
position:fixed;
top:0;
width:100%;
z-index:100;
}
Edit: You should have the element with position absolute, once the scroll offset has reached the element, it should be changed to fixed, and the top position should be set to zero.
You can detect the top scroll offset of the document with the scrollTop function:
$(window).scroll(function(e){
var $el = $('.fixedElement');
var isPositionFixed = ($el.css('position') == 'fixed');
if ($(this).scrollTop() > 200 && !isPositionFixed){
$el.css({'position': 'fixed', 'top': '0px'});
}
if ($(this).scrollTop() < 200 && isPositionFixed){
$el.css({'position': 'static', 'top': '0px'});
}
});
When the scroll offset reached 200, the element will stick to the top of the browser window, because is placed as fixed.

- 3,366
- 2
- 23
- 50

- 807,428
- 183
- 922
- 838
-
9that doesn't acchieve what I'm going for. I'd like the element to start at 200px below the top of the page (to allow room for other content) and then once the user has scrolled down become fixed at the top. – evanr Aug 01 '09 at 08:10
-
3your edit does indeed fill the needs of the question now but you still have a problem when the page scrolls back to the top again. you could after reaching the element scrollTop store it somewhere, and when the page hits that position again (when scrolling upwards) change the css back to default... probably better to do this with a .toggleClass then... – Sander Aug 02 '09 at 00:35
-
9This is pretty much what when with but I did have to remove the fixed positioning when the is window is scrolled back to the top. `if ($(this).scrollTop() < 200 && $el.css('position') == 'fixed') { $('.fixedElement').css({'position': 'static', 'top': '0px'}); }` – Derrick Petzold Mar 08 '12 at 20:46
-
1
-
-
1the `new example` link you gave is so much clean and clear that I can't even see it! -_- – sohaiby May 14 '15 at 14:50
-
1Thanks you for this code, But, when the div stick on the top, the width of div changes. Can we make it's width unchanged after sticky? Please help – VijayRana Jan 10 '18 at 19:23
-
I added/removed a class instead of doing all that stuff inside the scroll event. The class CSS makes the think sticky. – Edd Dec 15 '21 at 14:44
You've seen this example on Google Code's issue page and (only recently) on Stack Overflow's edit page.
CMS's answer doesn't revert the positioning when you scroll back up. Here's the shamelessly stolen code from Stack Overflow:
function moveScroller() {
var $anchor = $("#scroller-anchor");
var $scroller = $('#scroller');
var move = function() {
var st = $(window).scrollTop();
var ot = $anchor.offset().top;
if(st > ot) {
$scroller.css({
position: "fixed",
top: "0px"
});
} else {
$scroller.css({
position: "relative",
top: ""
});
}
};
$(window).scroll(move);
move();
}
<div id="sidebar" style="width:270px;">
<div id="scroller-anchor"></div>
<div id="scroller" style="margin-top:10px; width:270px">
Scroller Scroller Scroller
</div>
</div>
<script type="text/javascript">
$(function() {
moveScroller();
});
</script>
And a simple live demo.
A nascent, script-free alternative is position: sticky
, which is supported in Chrome, Firefox, and Safari. See the article on HTML5Rocks and demo, and Mozilla docs.

- 2,465
- 1
- 28
- 37

- 171,072
- 38
- 269
- 275
-
3For some reason, the {scroll:false} was giving me issues (jQuery 1.6.2). Seems work without it. [Fork](http://jsfiddle.net/bv5y5/embedded/result/) from linked demo. Any idea if it serves a purpose? – Eddie Sep 07 '11 at 15:23
-
I'm having alot of trouble with this, for the life of me I cannot replicate, i've even tried to replicate the live demo and its not working. can anyone link to a tutorial that provides step by step instructions? – Trevor Dupp Sep 21 '11 at 15:27
-
2This seems to work just fine, when I use the same version of jQuery as the demo (1.3.2). At some point `offset` must have stopped accepting an object as input http://api.jquery.com/offset/. @Eddie Your modification should be safe with current jQuery. – Graeme Dec 13 '11 at 21:02
-
1Is there any reason you couldn't replace `var d = $("#scroller-anchor").offset().top;` with `var d = $("#sidebar").offset().top;` and get rid of the empty scroller-anchor div all together? Here's my [fork](http://jsfiddle.net/thfRw/embedded/result/) demonstrating what I'm talking about. – Mike Deck Jan 27 '12 at 06:21
-
@MikeDeck I suspect that if there are margins or padding, you would like to be able to control where the scroller is positioned relative to the container. – Josh Lee Jan 27 '12 at 14:03
-
This script has some problems on browser like Safari Mobile, where the faster you scroll physically, the faster it goes. In this cases it takes some time before actually showing up. – Paolo Moretti Mar 10 '12 at 11:03
-
Could someone take a look at this: i am having trouble figuring it out: http://jsfiddle.net/Csf9S/ – Batman Feb 16 '13 at 14:07
-
@Josh you can completely get rid of the condition if(st <= ot) {} since it's always true... I forked your fiddle: http://fiddle.jshell.net/34df1mj7/show/light/ If you agree I'd update your answer – Felix Geenen Jul 14 '17 at 13:47
-
Thanks you for this code, But, when the div stick on the top, the width of div changes. Can we make it's width unchanged after sticky? Please help – VijayRana Jan 10 '18 at 19:24
As of January 2017 and the release of Chrome 56, most browsers in common use support the position: sticky
property in CSS.
#thing_to_stick {
position: sticky;
top: 0;
}
does the trick for me in Firefox and Chrome.
In Safari you still need to use position: -webkit-sticky
.
Polyfills are available for Internet Explorer and Edge; https://github.com/wilddeer/stickyfill seems to be a good one.

- 7,372
- 3
- 28
- 51
-
7This is supported in most browsers in common use today. See caniuse.com/#feat=css-sticky Secondly, I much prefer a solution which can be boiled down to 2 lines of code to a version that requires custom Javascript. And it's future-proof too. Use a polyfill if you're worried about browser compatibility. – Colin 't Hart Jan 26 '17 at 10:17
-
2I will like to add to this comment that we can z-index: 99999;, because if not when it goes to top, the other content will be rendered first. But this should be the accepted solution. – Dayán Ruiz Jun 21 '19 at 02:40
-
And here's how without jquery (UPDATE: see other answers where you can now do this with CSS only)
var startProductBarPos=-1;
window.onscroll=function(){
var bar = document.getElementById('nav');
if(startProductBarPos<0)startProductBarPos=findPosY(bar);
if(pageYOffset>startProductBarPos){
bar.style.position='fixed';
bar.style.top=0;
}else{
bar.style.position='relative';
}
};
function findPosY(obj) {
var curtop = 0;
if (typeof (obj.offsetParent) != 'undefined' && obj.offsetParent) {
while (obj.offsetParent) {
curtop += obj.offsetTop;
obj = obj.offsetParent;
}
curtop += obj.offsetTop;
}
else if (obj.y)
curtop += obj.y;
return curtop;
}
* {margin:0;padding:0;}
.nav {
border: 1px red dashed;
background: #00ffff;
text-align:center;
padding: 21px 0;
margin: 0 auto;
z-index:10;
width:100%;
left:0;
right:0;
}
.header {
text-align:center;
padding: 65px 0;
border: 1px red dashed;
}
.content {
padding: 500px 0;
text-align:center;
border: 1px red dashed;
}
.footer {
padding: 100px 0;
text-align:center;
background: #777;
border: 1px red dashed;
}
<header class="header">This is a Header</header>
<div id="nav" class="nav">Main Navigation</div>
<div class="content">Hello World!</div>
<footer class="footer">This is a Footer</footer>

- 4,866
- 1
- 27
- 43
-
4Thank you! Getting hard to find native JS solutions these days. This worked perfectly. – Sherri May 07 '15 at 19:36
-
Thank you so much, this worked perfectly since jquery was conflicting with some legacy enterprise code my project has – sng Apr 27 '16 at 23:59
-
though im running into a problem where if I scroll to the bottom of the page it will automatically pop me back up to the top. – sng Apr 28 '16 at 03:02
-
-
@JimW I found out the issue. I was trying to use it with a vertical based menu bar next to a main content div to the left. It was bugging out when you scroll down since it can't determine when it's hitting the bottom of the page properly. I ended up adding a line of code to set the container div height to the window screen size to the scroll event listener – sng May 10 '16 at 06:41
-
There is an issue with this solution because the content "jumps" up. It's easier to see it with smaller `padding-top`. Demo: https://jsbin.com/fivugux/edit?html,css,js,output – Mosh Feu Apr 14 '22 at 23:40
I had the same problem as you and ended up making a jQuery plugin to take care of it. It actually solves all the problems people have listed here, plus it adds a couple of optional features too.
Options
stickyPanelSettings = {
// Use this to set the top margin of the detached panel.
topPadding: 0,
// This class is applied when the panel detaches.
afterDetachCSSClass: "",
// When set to true the space where the panel was is kept open.
savePanelSpace: false,
// Event fires when panel is detached
// function(detachedPanel, panelSpacer){....}
onDetached: null,
// Event fires when panel is reattached
// function(detachedPanel){....}
onReAttached: null,
// Set this using any valid jquery selector to
// set the parent of the sticky panel.
// If set to null then the window object will be used.
parentSelector: null
};

- 22,248
- 13
- 65
- 79
-
1Hey! Thank you! This is a great solution, and thanks for sharing, for sure it saved me a lot of time. This should be the overall accepted solution for this question, since as far as I have read, it is the most complete solution. Basically, the others did not solve the problem with the original X-position of a block after the position: fixed style is applied. Yours solves this problem. Really, many thanks! – Marcos Buarque Oct 27 '11 at 15:37
-
Hey Donny, also love your plugin (v1.4.1)... did come across one issue, Block elelments lost their width if none was specified. So altered it when detaching... only by setting the width so it remains the same. `code`// detach panel node.css({ "margin": 0, "left": nodeLeft, "top": newNodeTop, "position": "fixed", "width": node.width() });`code` – Will Hancock Nov 17 '11 at 17:31
-
Looked for and tried many solutions, and this worked "right out of the box." Amazing work! Thank you! – AJ Tatum Apr 02 '12 at 22:04
-
2@WillHancock I'v added iPad support, fixed the refresh bug and added onDetached & onReattached events. The new events will give you access to the panel & spacerpanel after it has detached & reattached. – Donny V. Nov 20 '12 at 15:00
-
4
-
It only remains sticky as long as its container is in the window when the container gets scrolled up, – Siraj Alam Sep 12 '19 at 06:50
The simplest solution (without js) : demo
.container {
position: relative;
}
.sticky-div {
position: sticky;
top: 0;
}
<div class="container">
<h1>
relative container & sticky div
</h1>
<div class="sticky-div"> this row is sticky</div>
<div>
content
</div>
</div>

- 1,213
- 1
- 12
- 28
This is how i did it with jquery. This was all cobbled together from various answers on stack overflow. This solution caches the selectors for faster performance and also solves the "jumping" issue when the sticky div becomes sticky.
Check it out on jsfiddle: http://jsfiddle.net/HQS8s/
CSS:
.stick {
position: fixed;
top: 0;
}
JS:
$(document).ready(function() {
// Cache selectors for faster performance.
var $window = $(window),
$mainMenuBar = $('#mainMenuBar'),
$mainMenuBarAnchor = $('#mainMenuBarAnchor');
// Run this on scroll events.
$window.scroll(function() {
var window_top = $window.scrollTop();
var div_top = $mainMenuBarAnchor.offset().top;
if (window_top > div_top) {
// Make the div sticky.
$mainMenuBar.addClass('stick');
$mainMenuBarAnchor.height($mainMenuBar.height());
}
else {
// Unstick the div.
$mainMenuBar.removeClass('stick');
$mainMenuBarAnchor.height(0);
}
});
});

- 345
- 3
- 9
As Josh Lee and Colin 't Hart have said, you could optionally just use position: sticky; top: 0;
applying to the div that you want the scrolling at...
Plus, the only thing you will have to do is copy this into the top of your page or format it to fit into an external CSS sheet:
<style>
#sticky_div's_name_here { position: sticky; top: 0; }
</style>
Just replace #sticky_div's_name_here
with the name of your div, i.e. if your div was <div id="example">
you would put #example { position: sticky; top: 0; }
.

- 146
- 2
- 9
Here is another option:
JAVASCRIPT
var initTopPosition= $('#myElementToStick').offset().top;
$(window).scroll(function(){
if($(window).scrollTop() > initTopPosition)
$('#myElementToStick').css({'position':'fixed','top':'0px'});
else
$('#myElementToStick').css({'position':'absolute','top':initTopPosition+'px'});
});
Your #myElementToStick
should start with position:absolute
CSS property.

- 401
- 1
- 6
- 14
-
1I think this is a very clean and easy solution. I just would not position the element "absolute" - this might break the layout - I would just set it to static. – ESP32 Jul 05 '17 at 08:30
Here's one more version to try for those having issues with the others. It pulls together the techniques discussed in this duplicate question, and generates the required helper DIVs dynamically so no extra HTML is required.
CSS:
.sticky { position:fixed; top:0; }
JQuery:
function make_sticky(id) {
var e = $(id);
var w = $(window);
$('<div/>').insertBefore(id);
$('<div/>').hide().css('height',e.outerHeight()).insertAfter(id);
var n = e.next();
var p = e.prev();
function sticky_relocate() {
var window_top = w.scrollTop();
var div_top = p.offset().top;
if (window_top > div_top) {
e.addClass('sticky');
n.show();
} else {
e.removeClass('sticky');
n.hide();
}
}
w.scroll(sticky_relocate);
sticky_relocate();
}
To make an element sticky, do:
make_sticky('#sticky-elem-id');
When the element becomes sticky, the code manages the position of the remaining content to keep it from jumping into the gap left by the sticky element. It also returns the sticky element to its original non-sticky position when scrolling back above it.
-
Your approach is very similar to [JohnB's approach](http://stackoverflow.com/a/15627431/718325). Considering your differences to that answer, I'm wondering (1) Is there an advantage to using a second "helper div" (instead of just 1 like JohnB uses), and (2) Is there an advantage to using hide() and show() instead of just setting the helper div's height (like JohnB does)? Perhaps a performance difference? So far I haven't been able to discern differences but perhaps certain scenarios would have differences (like maybe involving inline elements or something), so that's why I ask. Thanks. – Jason Frank May 07 '14 at 20:51
My solution is a little verbose, but it handles variable positioning from the left edge for centered layouts.
// Ensurs that a element (usually a div) stays on the screen
// aElementToStick = The jQuery selector for the element to keep visible
global.makeSticky = function (aElementToStick) {
var $elementToStick = $(aElementToStick);
var top = $elementToStick.offset().top;
var origPosition = $elementToStick.css('position');
function positionFloater(a$Win) {
// Set the original position to allow the browser to adjust the horizontal position
$elementToStick.css('position', origPosition);
// Test how far down the page is scrolled
var scrollTop = a$Win.scrollTop();
// If the page is scrolled passed the top of the element make it stick to the top of the screen
if (top < scrollTop) {
// Get the horizontal position
var left = $elementToStick.offset().left;
// Set the positioning as fixed to hold it's position
$elementToStick.css('position', 'fixed');
// Reuse the horizontal positioning
$elementToStick.css('left', left);
// Hold the element at the top of the screen
$elementToStick.css('top', 0);
}
}
// Perform initial positioning
positionFloater($(window));
// Reposition when the window resizes
$(window).resize(function (e) {
positionFloater($(this));
});
// Reposition when the window scrolls
$(window).scroll(function (e) {
positionFloater($(this));
});
};

- 3,080
- 2
- 41
- 62
Here is an extended version to Josh Lee's answer. If you want the div to be on sidebar to the right, and float within a range (i.e., you need to specify top and bottom anchor positions). It also fixes a bug when you view this on mobile devices (you need to check left scroll position otherwise the div will move off screen).
function moveScroller() {
var move = function() {
var st = $(window).scrollTop();
var sl = $(window).scrollLeft();
var ot = $("#scroller-anchor-top").offset().top;
var ol = $("#scroller-anchor-top").offset().left;
var bt = $("#scroller-anchor-bottom").offset().top;
var s = $("#scroller");
if(st > ot) {
if (st < bt - 280) //280px is the approx. height for the sticky div
{
s.css({
position: "fixed",
top: "0px",
left: ol-sl
});
}
else
{
s.css({
position: "fixed",
top: bt-st-280,
left: ol-sl
});
}
} else {
s.css({
position: "relative",
top: "",
left: ""
});
}
};
$(window).scroll(move);
move();
}

- 305
- 3
- 7
I came across this when searching for the same thing. I know it's an old question but I thought I'd offer a more recent answer.
Scrollorama has a 'pin it' feature which is just what I was looking for.

- 11
- 1
The info provided to answer this other question may be of help to you, Evan:
Check if element is visible after scrolling
You basically want to modify the style of the element to set it to fixed only after having verified that the document.body.scrollTop value is equal to or greater than the top of your element.
I used some of the work above to create this tech. I improved it a bit and thought I would share my work. Hope this helps.
function scrollErrorMessageToTop() {
var flash_error = jQuery('#flash_error');
var flash_position = flash_error.position();
function lockErrorMessageToTop() {
var place_holder = jQuery("#place_holder");
if (jQuery(this).scrollTop() > flash_position.top && flash_error.attr("position") != "fixed") {
flash_error.css({
'position': 'fixed',
'top': "0px",
"width": flash_error.width(),
"z-index": "1"
});
place_holder.css("display", "");
} else {
flash_error.css('position', '');
place_holder.css("display", "none");
}
}
if (flash_error.length > 0) {
lockErrorMessageToTop();
jQuery("#flash_error").after(jQuery("<div id='place_holder'>"));
var place_holder = jQuery("#place_holder");
place_holder.css({
"height": flash_error.height(),
"display": "none"
});
jQuery(window).scroll(function(e) {
lockErrorMessageToTop();
});
}
}
scrollErrorMessageToTop();
This is a little bit more dynamic of a way to do the scroll. It does need some work and I will at some point turn this into a pluging but but this is what I came up with after hour of work.

- 5,521
- 11
- 50
- 73

- 3,250
- 3
- 24
- 22
In javascript you can do:
var element = document.getElementById("myid");
element.style.position = "fixed";
element.style.top = "0%";

- 2,638
- 6
- 31
- 41
Here's an example that uses jquery-visible plugin: http://jsfiddle.net/711p4em4/.
HTML:
<div class = "wrapper">
<header>Header</header>
<main>
<nav>Stick to top</nav>
Content
</main>
<footer>Footer</footer>
</div>
CSS:
* {
margin: 0;
padding: 0;
}
body {
background-color: #e2e2e2;
}
.wrapper > header,
.wrapper > footer {
font: 20px/2 Sans-Serif;
text-align: center;
background-color: #0040FF;
color: #fff;
}
.wrapper > main {
position: relative;
height: 500px;
background-color: #5e5e5e;
font: 20px/500px Sans-Serif;
color: #fff;
text-align: center;
padding-top: 40px;
}
.wrapper > main > nav {
position: absolute;
top: 0;
left: 0;
right: 0;
font: 20px/2 Sans-Serif;
color: #fff;
text-align: center;
background-color: #FFBF00;
}
.wrapper > main > nav.fixed {
position: fixed;
top: 0;
left: 0;
right: 0;
}
JS (include jquery-visible plugin):
(function($){
/**
* Copyright 2012, Digital Fusion
* Licensed under the MIT license.
* http://teamdf.com/jquery-plugins/license/
*
* @author Sam Sehnert
* @desc A small plugin that checks whether elements are within
* the user visible viewport of a web browser.
* only accounts for vertical position, not horizontal.
*/
var $w = $(window);
$.fn.visible = function(partial,hidden,direction){
if (this.length < 1)
return;
var $t = this.length > 1 ? this.eq(0) : this,
t = $t.get(0),
vpWidth = $w.width(),
vpHeight = $w.height(),
direction = (direction) ? direction : 'both',
clientSize = hidden === true ? t.offsetWidth * t.offsetHeight : true;
if (typeof t.getBoundingClientRect === 'function'){
// Use this native browser method, if available.
var rec = t.getBoundingClientRect(),
tViz = rec.top >= 0 && rec.top < vpHeight,
bViz = rec.bottom > 0 && rec.bottom <= vpHeight,
lViz = rec.left >= 0 && rec.left < vpWidth,
rViz = rec.right > 0 && rec.right <= vpWidth,
vVisible = partial ? tViz || bViz : tViz && bViz,
hVisible = partial ? lViz || rViz : lViz && rViz;
if(direction === 'both')
return clientSize && vVisible && hVisible;
else if(direction === 'vertical')
return clientSize && vVisible;
else if(direction === 'horizontal')
return clientSize && hVisible;
} else {
var viewTop = $w.scrollTop(),
viewBottom = viewTop + vpHeight,
viewLeft = $w.scrollLeft(),
viewRight = viewLeft + vpWidth,
offset = $t.offset(),
_top = offset.top,
_bottom = _top + $t.height(),
_left = offset.left,
_right = _left + $t.width(),
compareTop = partial === true ? _bottom : _top,
compareBottom = partial === true ? _top : _bottom,
compareLeft = partial === true ? _right : _left,
compareRight = partial === true ? _left : _right;
if(direction === 'both')
return !!clientSize && ((compareBottom <= viewBottom) && (compareTop >= viewTop)) && ((compareRight <= viewRight) && (compareLeft >= viewLeft));
else if(direction === 'vertical')
return !!clientSize && ((compareBottom <= viewBottom) && (compareTop >= viewTop));
else if(direction === 'horizontal')
return !!clientSize && ((compareRight <= viewRight) && (compareLeft >= viewLeft));
}
};
})(jQuery);
$(function() {
$(window).scroll(function() {
$(".wrapper > header").visible(true) ?
$(".wrapper > main > nav").removeClass("fixed") :
$(".wrapper > main > nav").addClass("fixed");
});
});

- 5,557
- 14
- 14
The accepted answer works but doesn't move back to previous position if you scroll above it. It is always stuck to the top after being placed there.
$(window).scroll(function(e) {
$el = $('.fixedElement');
if ($(this).scrollTop() > 42 && $el.css('position') != 'fixed') {
$('.fixedElement').css( 'position': 'fixed', 'top': '0px');
} else if ($(this).scrollTop() < 42 && $el.css('position') != 'relative') {
$('.fixedElement').css( 'relative': 'fixed', 'top': '42px');
//this was just my previous position/formating
}
});
jleedev's response whould work, but I wasn't able to get it to work. His example page also didn't work (for me).

- 501
- 2
- 9
You can add 3 extra rows so when the user scroll back to the top, the div will stick on its old place:
Here is the code:
if ($(this).scrollTop() < 200 && $el.css('position') == 'fixed'){
$('.fixedElement').css({'position': 'relative', 'top': '200px'});
}

- 9,833
- 3
- 32
- 58
I have links setup in a div so it is a vertical list of letter and number links.
#links {
float:left;
font-size:9pt;
margin-left:0.5em;
margin-right:1em;
position:fixed;
text-align:center;
width:0.8em;
}
I then setup this handy jQuery function to save the loaded position and then change the position to fixed when scrolling beyond that position.
NOTE: this only works if the links are visible on page load!!
var listposition=false;
jQuery(function(){
try{
///// stick the list links to top of page when scrolling
listposition = jQuery('#links').css({'position': 'static', 'top': '0px'}).position();
console.log(listposition);
$(window).scroll(function(e){
$top = $(this).scrollTop();
$el = jQuery('#links');
//if(typeof(console)!='undefined'){
// console.log(listposition.top,$top);
//}
if ($top > listposition.top && $el.css('position') != 'fixed'){
$el.css({'position': 'fixed', 'top': '0px'});
}
else if ($top < listposition.top && $el.css('position') == 'fixed'){
$el.css({'position': 'static'});
}
});
} catch(e) {
alert('Please vendor admin@mydomain.com (Myvendor JavaScript Issue)');
}
});

- 1,982
- 22
- 33
I had a similar problem - I had a div that was already floating in 'fixed' position above other content, defined by CSS. What I wanted to achieve was when I scrolled the page down, the div would start scrolling down with content but then stick to the top of the page (i.e. would never disappear).
The style of my div is:
.inProjectNavigation {
width: 60.5%;
max-width: 1300px;
position: fixed; top: 60%;
display: block;
}
I simply put this div somewhere on the page and it appears on top of content. There are no special requirements for the style of its parents.
The the JS to make it stick to the top is:
const MIN_TOP_POSITION = 30;
/**
* Make the project navigation initially scroll down with the page, but then stick to the top of the browser
*/
$(window).scroll(function(e){
let $navigationDiv = $('.inProjectNavigation');
let originalTopPosPx = $navigationDiv.attr('data-originalTopPosPx');
//-- on first scroll, save the original px position in the element, as defined by CSS
if (originalTopPosPx == null) {
let cssValue = $navigationDiv.css('top');
originalTopPosPx = cssValue.substring(0, cssValue.length - 2); // get rid of the 'px'
$navigationDiv.attr('data-originalTopPosPx', originalTopPosPx);
}
//-- follow the scroll, but stick to top
$navigationDiv.css({'top': Math.max(MIN_TOP_POSITION, (originalTopPosPx - $(this).scrollTop())) + 'px'});
});
Tested on a Mac - Safari, Firefox, Chrome. Hopefully should work in IE too :)

- 979
- 12
- 14
You can make it without using javascript by using :
.element_to_stick {
position: sticky;
top: 0px; // Top calculated from div Parent, not top screen !
}
In Safari you still need to use position: -webkit-sticky.

- 538
- 4
- 6
Not an exact solution but a great alternative to consider
this CSS ONLY Top of screen scroll bar. Solved all the problem with ONLY CSS, NO JavaScript, NO JQuery, No Brain work (lol).
Enjoy my fiddle :D all the codes are included in there :)
CSS
#menu {
position: fixed;
height: 60px;
width: 100%;
top: 0;
left: 0;
border-top: 5px solid #a1cb2f;
background: #fff;
-moz-box-shadow: 0 2px 3px 0px rgba(0, 0, 0, 0.16);
-webkit-box-shadow: 0 2px 3px 0px rgba(0, 0, 0, 0.16);
box-shadow: 0 2px 3px 0px rgba(0, 0, 0, 0.16);
z-index: 999999;
}
.w {
width: 900px;
margin: 0 auto;
margin-bottom: 40px;
}<br type="_moz">
Put the content long enough so you can see the effect here :) Oh, and the reference is in there as well, for the fact he deserve his credit

- 1,250
- 2
- 14
- 22
-
1
-
I am not against a good solution, but the code in your answer provides a way to make something like a menu to always stick on top. But that was not the question... – Tokk Feb 19 '14 at 12:45
-
you are just fixing the div and not doing anything sticky on scrolling. – yogihosting Nov 09 '15 at 05:48
-
As other's have pointed out, this doesn't make an element sticky on scroll, it's just always fixed to the top of the screen which of course can easily be done in css. It's the process of determing the scroll amount and then changing position: absolute -> fixed and removing it again that needs solving – Andrew West Nov 18 '21 at 09:54
-
no, no, no ... it is not what the OP asked. He want his element to scroll and stay sticky once it reached the top. – Aug 11 '22 at 16:44
sticky till the footer hits the div:
function stickyCostSummary() {
var stickySummary = $('.sticky-cost-summary');
var scrollCostSummaryDivPosition = $(window).scrollTop();
var footerHeight = $('#footer').height();
var documentHeight = $(document).height();
var costSummaryHeight = stickySummary.height();
var headerHeight = 83;
var footerMargin = 10;
var scrollHeight = 252;
var footerPosition = $('#footer').offset().top;
if (scrollCostSummaryDivPosition > scrollHeight && scrollCostSummaryDivPosition <= (documentHeight - footerHeight - costSummaryHeight - headerHeight - footerMargin)) {
stickySummary.removeAttr('style');
stickySummary.addClass('fixed');
} else if (scrollCostSummaryDivPosition > (documentHeight - footerHeight - costSummaryHeight - headerHeight - footerMargin)) {
stickySummary.removeClass('fixed');
stickySummary.css({
"position" : "absolute",
"top" : (documentHeight - footerHeight - costSummaryHeight - headerHeight - footerMargin - scrollHeight) + "px"
});
} else {
stickySummary.removeClass('fixed');
stickySummary.css({
"position" : "absolute",
"top" : "0"
});
}
}
$window.scroll(stickyCostSummary);