Sunday, May 19, 2024
 Popular · Latest · Hot · Upcoming
119
rated 0 times [  123] [ 4]  / answers: 1 / hits: 33600  / 10 Years ago, thu, october 30, 2014, 12:00:00
<div id=header></div>
<div id=sticky></div>
<div id=section></div>
<div id=footer></div>

<style>
body { margin: 0px; background-color: #e3e3e3; }
#header { background-color: #cb5454; height: 140px; }
#sticky { background-color: #546bcb; height: 70px; }
#section { height: 1500px; }
#footer { background-color: #cb5454; height: 140px; }
</style>


Here is my code: http://jsfiddle.net/uaqh018d/



I want #sticky to stick to the top of the page after scrolling past #header. I also want it hidden until stuck. And then of course have it unstick+hide again after scrolling back up to #header.



How can I achieve this?


More From » jquery

 Answers
263

I would recommend adding a class to #sticky when it's ready to be fixed to the top of the screen, and then removing that class when you want to 'unstick' it. Then you can manipulate that class in CSS.



e.g. for a class fixed you'd put the following in your CSS:



#sticky {
display: none;
background-color: #546bcb;
height: 70px;
}
#sticky.fixed {
display: block;
position: fixed;
top: 0;
width: 100%;
}


And then your jQuery would look like this:



$(window).scroll(function() {
var distanceFromTop = $(this).scrollTop();
if (distanceFromTop >= $('#header').height()) {
$('#sticky').addClass('fixed');
} else {
$('#sticky').removeClass('fixed');
}
});


Here's an updated FIDDLE



I might also recommend some jQuery fade or slide effects (see the fiddle).


[#68957] Tuesday, October 28, 2014, 10 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
mckaylab

Total Points: 311
Total Questions: 120
Total Answers: 93

Location: Montenegro
Member since Thu, Jun 16, 2022
2 Years ago
;