Make element fixed on scroll - javascript

I'm attempting to make the navigation bar stick to the top, when the user scrolls down to the nav bar and then unstick when the user scrolls back up past the navbar. I understand that this can only be implemented via JavaScript. I'm a beginner to JavaScript, so the easier the better. The JSFIDDLE is here.
The HTML is as follows:
<section class="main">
<div id="wrap">
<div id="featured">
<div class="wrap">
<div class="textwidget">
<div class="cup"><img src="#""></div>
<div id="header"></div></div></div></div></div></div></div>
<div class="whiteboard">
<h1>HELLO GUYS</h1> </div>
</div>
<div class="bg1">
<h2> WE ARE AN EVENTS MANAGEMENT COMPANY BASED IN LONDON. </h2></div>
The CSS is as follows:
.main{text-align:center;}
h1{
-webkit-font-smoothing: antialiased;
display:inline-block;
font: 800 1.313em "proxima-nova",sans-serif;
padding: 10px 10px;
margin: 20px 20px;
letter-spacing: 8px;
text-transform: uppercase;
font-size:3.125em;
text-align: center;
max-width: 606px;
line-height: 1.45em;
position: scroll;
background-color:#e94f78;
text-decoration: none;
color:yellow;
background-image:url;
}
h1 a{
text-decoration: none;
color:yellow;
padding-left: 0.15em;
}
h2{
-webkit-font-smoothing: antialiased;
display:inline-block;
font: 800 1.313em "proxima-nova",sans-serif;
letter-spacing: 8px;
margin-top: 100px;
text-transform: uppercase;
font-size:3.125em;
text-align: center;
line-height: 1.45em;
position: scroll;
text-decoration: none;
color:white;
z-index: -9999;
}
h2 a{
text-decoration: none;
color:white;
padding-left: 0.15em;
}
h5{
position: absolute;
font-family:sans-serif;
font-weight:bold;
font-size:40px;
text-align: center;
float: right;
background-color:#fff;
margin-top: -80px;
margin-left: 280px;
}
h5 a{
text-decoration: none;
color:red;
}
h5 a:hover{
color:yellow;
}
#text1{
-webkit-font-smoothing: antialiased;
display:inline-block;
font: 800 1.313em "proxima-nova",sans-serif;
margin: 20px 20px;
letter-spacing: 8px;
text-transform: uppercase;
font-size:3.125em;
text-align: center;
max-width: 606px;
line-height: 1.45em;
position: scroll;
background-color:#E94F78;
}
#text1 a{
color:yellow;
text-decoration: none;
padding-left: 0.15em;
}
#text1 a:hover{
text-decoration: none;
cursor:pointer;
}
.whiteboard{
background-image:url(http://krystalrae.com/img/krystalrae-2012-fall-print-leopard-sketch.jpg);
background-position: center;
padding: ;
background-color: #fff;
z-index: 1000;
}
.bg{
height:2000px;
background-color:#ff0;
background-image:url(http://alwayscreative.net/images/stars-last.jpg);
position:relative;
z-index: -9999;
}
.bg1{
background-image:url(http://alwayscreative.net/images/stars-last.jpg);
z-index: -9999;
height:1000px;
}
/* Header */
#wrap {
margin: 0 auto;
padding: 0;
width: 100%;
}
#featured {
background: #E94F78 url(http://www.creativityfluid.com/wp-content/themes/creativityfluid/images/img-bubbles-red.png) no-repeat top;
background-size: 385px 465px;
color: #fff;
height: 535px;
overflow: hidden;
position: relative;
z-index: -2;
}
#featured .wrap {
overflow: hidden;
clear: both;
padding: 70px 0 30px;
position: fixed;
z-index: -1;
width: 100%;
}
#featured .wrap .widget {
width: 80%;
max-width: 1040px;
margin: 0 auto;
}
#featured h1,
#featured h3,
#featured p {
color: yellow;
text-shadow: none;
}
#featured h4{
color:white;
text-shadow:none;
}
#featured h4 {
margin: 0 0 30px;
}
#featured h3 {
font-family: 'proxima-nova-sc-osf', arial, serif;
font-weight: 600;
letter-spacing: 3px;
}
#featured h1 {
margin: 0;
}
.textwidget{
padding: 0;
}
.cup{
margin-top:210px;
z-index: 999999;
}
.container{font-size:14px; margin:0 auto; width:960px}
.test_content{margin:10px 0;}
.scroller_anchor{height:0px; margin:0; padding:0;background-image:url()}
.scroller{background:#FFF;
background-image:url(http://krystalrae.com/img/krystalrae-2012-fall-print-leopard-sketch.jpg);
margin:0 0 10px; z-index:100; height:50px; font-size:18px; font-weight:bold; text-align:center; width:960px;}

You can do that with some easy jQuery:
http://jsfiddle.net/jpXjH/6/
var elementPosition = $('#navigation').offset();
$(window).scroll(function(){
if($(window).scrollTop() > elementPosition.top){
$('#navigation').css('position','fixed').css('top','0');
} else {
$('#navigation').css('position','static');
}
});

I wouldn't bother with jQuery or LESS. A javascript framework is overkill in my opinion.
window.addEventListener('scroll', function (evt) {
// This value is your scroll distance from the top
var distance_from_top = document.body.scrollTop;
// The user has scrolled to the tippy top of the page. Set appropriate style.
if (distance_from_top === 0) {
}
// The user has scrolled down the page.
if(distance_from_top > 0) {
}
});

There are some problems implementing this which the original accepted answer does not answer:
The onscroll event of the window is firing very often. This
implies that you either have to use a very performant listener, or
you have to delay the listener somehow. jQuery Creator John Resig
states here how a
delayed mechanism can be implemented, and the reasons why you should
do it. In my opinion, given todays browsers and environments, a
performant listener will do as well. Here is an implementation of the pattern suggested by John Resig
The way position:fixed works in css, if you scroll down the page and move an element from position:static to position: fixed, the page will "jump" a little because the document "looses" the height of the element. You can get rid of that by adding the height to the scrollTop and replace the lost height in the document body with another object. You can also use that object to determine if the sticky item has already been moved to position: fixed and reduce the calls to the code reverting position: fixed to the original state: Look at the fiddle here
Now, the only expensive thing in terms of performance the handler is really doing is calling scrollTop on every call. Since the interval bound handler has also its drawbacks, I'll go as far as to argue here that you can reattach the event listener to the original scroll Event to make it feel snappier without many worries. You'll have to profile it though, on every browser you target / support. See it working here
Here's the code:
JS
/* Initialize sticky outside the event listener as a cached selector.
* Also, initialize any needed variables outside the listener for
* performance reasons - no variable instantiation is happening inside the listener.
*/
var sticky = $('#sticky'),
stickyClone,
stickyTop = sticky.offset().top,
scrollTop,
scrolled = false,
$window = $(window);
/* Bind the scroll Event */
$window.on('scroll', function (e) {
scrollTop = $window.scrollTop();
if (scrollTop >= stickyTop && !stickyClone) {
/* Attach a clone to replace the "missing" body height */
stickyClone = sticky.clone().prop('id', sticky.prop('id') + '-clone')
stickyClone = stickyClone.insertBefore(sticky);
sticky.addClass('fixed');
} else if (scrollTop < stickyTop && stickyClone) {
/* Since sticky is in the viewport again, we can remove the clone and the class */
stickyClone.remove();
stickyClone = null;
sticky.removeClass('fixed');
}
});
CSS
body {
margin: 0
}
.sticky {
padding: 1em;
background: black;
color: white;
width: 100%
}
.sticky.fixed {
position: fixed;
top: 0;
left: 0;
}
.content {
padding: 1em
}
HTML
<div class="container">
<div id="page-above" class="content">
<h2>Some Content above sticky</h2>
...some long text...
</div>
<div id="sticky" class="sticky">This is sticky</div>
<div id="page-content" class="content">
<h2>Some Random Page Content</h2>...some really long text...
</div>
</div>

Here you go, no frameworks, short and simple:
var el = document.getElementById('elId');
var elTop = el.getBoundingClientRect().top - document.body.getBoundingClientRect().top;
window.addEventListener('scroll', function(){
if (document.documentElement.scrollTop > elTop){
el.style.position = 'fixed';
el.style.top = '0px';
}
else
{
el.style.position = 'static';
el.style.top = 'auto';
}
});

You want to use jQuery WayPoints. It is a very simple plugin and acheives exactly what you have described.
Most straightforward implementation
$('.thing').waypoint(function(direction) {
alert('Top of thing hit top of viewport.');
});
You will need to set some custom CSS to set exactly where it does become stuck, this is normal though for most ways to do it.
This page will show you all the examples and info that you need.
For future reference a example of it stopping and starting is this website. It is a "in the wild" example.

You can go to LESS CSS website http://lesscss.org/
Their dockable menu is light and performs well. The only caveat is that the effect takes place after the scroll is complete. Just do a view source to see the js.

You can do this with css too.
just use position:fixed;
for what you want to be fixed when you scroll down.
you can have some examples here:
http://davidwalsh.name/demo/css-fixed-position.php
http://demo.tutorialzine.com/2010/06/microtut-how-css-position-works/demo.html

window.addEventListener("scroll", function(evt) {
var pos_top = document.body.scrollTop;
if(pos_top == 0){
$('#divID').css('position','fixed');
}
else if(pos_top > 0){
$('#divId').css('position','static');
}
});

Plain Javascript Solution (DEMO) :
<br/><br/><br/><br/><br/><br/><br/>
<div>
<div id="myyy_bar" style="background:red;"> Here is window </div>
</div>
<br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/>
<script type="text/javascript">
var myyElement = document.getElementById("myyy_bar");
var EnableConsoleLOGS = true; //to check the results in Browser's Inspector(Console), whenever you are scrolling
// ==============================================
window.addEventListener('scroll', function (evt) {
var Positionsss = GetTopLeft ();
if (EnableConsoleLOGS) { console.log(Positionsss); }
if (Positionsss.toppp > 70) { myyElement.style.position="relative"; myyElement.style.top = "0px"; myyElement.style.right = "auto"; }
else { myyElement.style.position="fixed"; myyElement.style.top = "100px"; myyElement.style.right = "0px"; }
});
function GetOffset (object, offset) {
if (!object) return;
offset.x += object.offsetLeft; offset.y += object.offsetTop;
GetOffset (object.offsetParent, offset);
}
function GetScrolled (object, scrolled) {
if (!object) return;
scrolled.x += object.scrollLeft; scrolled.y += object.scrollTop;
if (object.tagName.toLowerCase () != "html") { GetScrolled (object.parentNode, scrolled); }
}
function GetTopLeft () {
var offset = {x : 0, y : 0}; GetOffset (myyElement.parentNode, offset);
var scrolled = {x : 0, y : 0}; GetScrolled (myyElement.parentNode.parentNode, scrolled);
var posX = offset.x - scrolled.x; var posY = offset.y - scrolled.y;
return {lefttt: posX , toppp: posY };
}
// ==============================================
</script>

The solution that worked for me lately is:
.sticky {
position: fixed;
top: 0;
width: 100%;
}
var header = document.getElementById("filters-tab");
var sticky = header.offsetTop;
if (window.pageYOffset > sticky) {
header.classList.add("fixed");
} else {
header.classList.remove("fixed");
}

Javascript is no longer required for this.
Do this using the CSS position:sticky property
https://css-tricks.com/position-sticky-2/

Related

Can I use requestAnimationFrame to smooth out scroll behaviour?

I have a small scroll effect which simulate that a logo will disappear if a lower div will scroll over it.
Currently I'm checking if two divs are intersecting. If this is true, then the height of the div of the logo will decrease with the scroll position of the div beneath.
Unfortunately, my demo is not foolproof and some fragments of the logo are still visible.
Is there a way to do this jank-free? Maybe with requestAnimationFrame?
function elementsOverlap(el1, el2) {
const domRect1 = el1.getBoundingClientRect();
const domRect2 = el2.getBoundingClientRect();
return !(
domRect1.top > domRect2.bottom ||
domRect1.right < domRect2.left ||
domRect1.bottom < domRect2.top ||
domRect1.left > domRect2.right
);
}
const el1 = document.querySelector(".logo");
const el2 = document.querySelector(".clickblocks");
let scrollPositionEl2;
let heightDifference;
const logoHeight = el1.offsetHeight;
document.addEventListener("DOMContentLoaded", () => {
var scrollDirectionDown;
scrollDirectionDown = true;
window.addEventListener("scroll", () => {
if (this.oldScroll > this.scrollY) {
scrollDirectionDown = false;
} else {
scrollDirectionDown = true;
}
this.oldScroll = this.scrollY;
// test
if (scrollDirectionDown) {
if (elementsOverlap(el1, el2) === true) {
scrollPositionEl2 = el2.getBoundingClientRect().top;
heightDifference = logoHeight - scrollPositionEl2 + 100;
//console.log(logoHeight - heightDifference);
el1.style.height = `${logoHeight - heightDifference}px`;
}
} else {
//scrolling up
scrollPositionEl2 = el2.getBoundingClientRect().top - 100;
el1.style.height = `${scrollPositionEl2}px`;
//console.log(logoHeight);
}
});
});
#import url("https://fonts.googleapis.com/css2?family=Inter:wght#900&display=swap");
.wrapper {
max-width: 100vw;
margin: 0 auto;
background-image: url("https://picsum.photos/1920/1080");
background-size: cover;
background-attachment: fixed;
height: 1200px;
position: relative;
&::after {
content: "";
position: absolute;
background: rgba(0, 0, 0, 0.3);
width: 100%;
height: 100%;
inset: 0;
}
}
body {
margin: 0;
}
main {
width: 100%;
height: 100vh;
position: relative;
z-index: 1;
}
.clickblocks {
width: 100%;
height: 200px;
display: grid;
grid-template-columns: repeat(12, (minmax(0, 1fr)));
}
.clickblock {
transition: all ease-in-out 0.2s;
backdrop-filter: blur(0px);
border: 1px solid #fff;
height: 100%;
grid-column: span 6 / span 6;
font-size: 54px;
font-weight: 700;
padding: 24px;
font-family: "Inter", sans-serif;
color: white;
text-transform: uppercase;
&:hover {
backdrop-filter: blur(10px);
}
}
.logo {
background: url("https://svgshare.com/i/ivR.svg");
width: 100%;
background-repeat: no-repeat;
background-position: top;
position: fixed;
top: 100px;
}
.logo-wrapper {
position: relative;
}
<div class="wrapper">
<main>
<div class="logo-wrapper" style="height: 390px">
<div class="logo" style="height: 300px">
</div>
</div>
<div class="clickblocks">
<div class="clickblock">
Some Content
</div>
</div>
</main>
</div>
Few things here to optimize your performance.
getBoundingClientRect() is a rather expensive calculation. If there are NO other options it's fine.
The Intersection Observer API is a lot more performant, and you can set the root element on the API. Then observe the element that is moving. This should be able to telly you if their are colliding.
Whenever you do scroll based logic, you should really try and throttle the logic so that the scroll any fires ever 16.6ms. That will reduce the number of times the calculations are made, and speed things up on the FE.
Learn how to use Google Chrome's performance tab. It can be overwhelming at first, but it gives you the ability to drill into the exact piece of code that's slowing your site down.
Learn about JS's event loop, and what's really going on under the hood. This video by Jake Archibald really help me understand it.
Hope this helped, sorry that I didn't give you an actual solution.

I'm trying to make my navbar retract upwards when I scroll down and then appear again when I scroll up, but it doesn't do anything

I'm very new to writing code but I've seen this done the same way, I don't get why it does nothing. The issue is likely somewhere in the CSS part.
JavaScript
var navbar = document.getElementsByClassName("navbar");
var lastY = window.pageYOffset;
window.onscroll = function()
{
var currY = window.pageYOffset;
if (lastY > currY)
{
document.getElementsByClassName("navbar").style.top = "0";
}
else
{
document.getElementsByClassName("navbar").style.top = "-50px";
}
lastY = currY;
}
HTML- I'm not exactly sure why I have to put all the links in their separate navbar-items class divs, but if I don't do this they start overlapping the header (i want the navbar to have that name on the left and the links on the right) and also make the other contents of the page after the navbar vanish.
<div class="navbar">
<h1>Квартална кръчма Тримата глупаци</h1>
<div class="navbar-items">
<div class="navbar-items">Home</div>
<div class="navbar-items"><a style="color:red;" href="Menu.html">Menu</a></div>
<div class="navbar-items">About us</div>
<div class="navbar-items">Contact us</div>
</div>
</div>
CSS
.navbar {
overflow: hidden;
position: fixed;
display: flex;
align-items: center;
justify-content: space-between;
background:#505d61;
z-index: 99;
padding: 10px;
height: 60px;
top: 0;
width: 100%;
box-shadow: 0 0 10px black;
}
.navbar-items {
overflow: hidden;
float:left;
display:block;
margin-left: 40px;
margin-right: 5px;
gap: 80px;
font-size: 21px;
font-weight: 550;
}
.navbar a{
color:black;
text-decoration: none;
}
.navbar a:hover{
color: white;
}
As the comment from CBroe points to, you issue is that you are expecting an element back from document.getElementsByClassName("navbar") but you are actually getting back an array. To access the element you need to pull it out of the array, you can do this like document.getElementsByClassName("navbar")[0].
So updating your code to
var lastY = window.pageYOffset;
window.onscroll = function(){
var currY = window.pageYOffset;
if (lastY > currY){
document.getElementsByClassName("navbar")[0].style.top = "0";
}
else{
document.getElementsByClassName("navbar")[0].style.top = "-50px";
}
lastY = currY;
}
Should fix the issue.

Not able to make element stick to the bottom when offscreen in IE 11, just like in css sticky

I am trying to replicate the same behavior as in this
codepen in IE 11 (does not have css sticky)
I am able to detect when the item is offscreen at the start with:
if (
$(".main-content").height() + $(".main-content").offset().top <
$(".main-footer").offset().top
)
but then after it reaches the end of the scroll (in this case the page), I did not manage to check when it goes offscreen again. It is probably something simple as subtracting the scroll to figure out if the element is offscreen, I am just stuck...
Here is a codepen where I stuck am now.
IE doesn't support <main> so you can't use this tag in IE 11. You can monitor the scroll bar changes through JavaScript, and then change its class according to the position of the element.
Here is the code you can refer to:
$(document).scroll(function() {
var scroH = $(document).scrollTop();
var viewH = $(window).height();
var contentH = $(document).height();
$('.main-footer').addClass('main-footer1')
if (scroH > 100) {}
if (contentH - (scroH + viewH) <= 100) { // The height from the bottom is less than 100px
}
if (contentH <= (scroH + viewH + 100)) {
$('.main-footer').removeClass('main-footer1')
$('.main-footer').addClass('main-footer2')
} else {
$('.main-footer').addClass('main-footer1')
$('.main-footer').removeClass('main-footer2')
}
});
body {
color: #fff;
font-family: arial;
font-weight: bold;
font-size: 40px;
}
.main-container {
max-width: 600px;
margin: 0 auto;
border: solid 10px green;
padding: 10px;
margin-top: 40px;
}
.main-container * {
padding: 10px;
background: #aaa;
border: dashed 5px #000;
}
.main-container *+* {
margin-top: 20px;
}
.main-header {
height: 50px;
background: #aaa;
}
.main-content {
min-height: 1000px;
}
.main-footer {
border-color: red;
}
.main-footer1 {
position: fixed;
bottom: 0px;
margin: 0 auto;
width: 570px;
}
.main-footer2 {
position: relative;
margin-top: 20px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="main-container">
<header class="main-header">HEADER</header>
<div class="main-content">MAIN contentH</div>
<footer class="main-footer">footer</footer>
</div>
Result in IE 11:

responsive height of div: shrink to a breakpoint then start growing again

I'm using an hero section to show some content.
It's responsive using the padding-bottom percentage technique and an inner absolute positioned container to center the content.
Now the catch: reaching a breakpoint, let's say 768px, and on lower window size I would like the box to start growing again.
I found some js/jQuery code around the web and was able to get the result but it only works if I load the page when the window is <768px. In that case it works brilliantly. But if the page is loaded in a larger window the below 768px resizing get lost.
This is the html:
<div class="row row-home-hero" id="hero">
<div class="cont">
<h1>Title</h1>
<h2>Subtitle</h2>
<div class="cta-hero-home">
» CTA1
<span class="cta-hero-spacer">or</span>
» CTA2
</div>
</div>
</div>
This is the JS.
It's a mess since it's a mix from different sources.
And I'm using Wordpress so I've to replace some $ with jQuery.
Please forgive me :)
function screenClass() {
if(jQuery(window).innerWidth() < 768) {
jQuery('.row-home-hero').addClass('small-hero');
} else {
jQuery('.row-home-hero').removeClass('small-hero');
jQuery('.row-home-hero').css("height", "");
}
}
// Fire.
screenClass();
// And recheck if window gets resized.
jQuery(window).bind('resize',function(){
screenClass();
});
if (document.documentElement.clientWidth < 768) {
var $li = jQuery('.small-hero'), // Cache your element
startW = $li.width(); // Store a variable reference
function setMarginDiff() {
area = 500000;
width = jQuery('.small-hero').width();
jQuery('.small-hero').height(Math.ceil(area/width/1.7));
}
setMarginDiff(); // Do on DOM ready
jQuery(window).resize(setMarginDiff); // and on resize
}
And this is the CSS
.row-home-hero {
background-position: center;
-webkit-background-size: cover;
background-size: cover;
background-repeat: no-repeat;
position: relative;
background-color: red;
}
.row-home-hero:before {
display: block;
content: "";
width: 100%;
padding-top: 46%;
}
.row-home-hero .cont {
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
width: 40%;
text-align: center;
}
a.cta-hero-link {
display: block;
width: 100px;
max-width: 80%;
line-height: 40px;
background: white;
color: #1b9fdd;
text-transform: uppercase;
text-decoration: none;
margin: 10px auto;
text-align: center;
font-weight: 500;
box-shadow: 0px 0px 7px 1px rgba(0,0,0,.4);
}
#media screen and (max-width: 768px) {
.row-pre-footer .cont div {
width: 100%;
padding: 0 5%;
float: none;
margin: 0 auto 30px;
}
.progetto-footer, .loghi-footer {
width: 100%;
max-width: 320px;
margin: 0 auto 30px;
float: none;
}
.double-box .tib-tab {
float: none;
width: 90%;
margin: 5% auto;
padding-bottom: 90%;
}
.tib-box h2, .tab-box h2 {
font-size: calc(28px + (46 - 28) * (100vw - 320px) / (768 - 320));
margin-bottom: 18vw;
}
.double-box-inner p {
font-size: 22px;
line-height: 30px;
}
.row-home-hero.small-hero {
height: 500px;
}
.row-home-hero:before {
display: block;
content: "";
width: 100%;
padding-top: 0;
}
}
And this is a working demo
Thanks!
I moved the if (document.documentElement.clientWidth < 768) { block inside the resize event. So that it gets called whenever the window is resized.
In the original version, it would only get called when the page was loaded (and only if the screen was smaller than 768). With this adjustment, it will always be rechecked when resized.
I also merged all your code into one smaller function.
var breakpoint = 768
var area = 500000
var target = $('.row-home-hero')
$(window).bind('resize', function() {
if(window.innerWidth < breakpoint) {
var width = target.width()
target.addClass('small-hero')
target.height(Math.ceil(area / width / 1.7))
} else {
target.removeClass('small-hero')
target.css('height', '')
}
})
.trigger('resize')

Content that scrolls with page, but is inside a fixed positioned sidebar (with shadow effect)

I'm trying to develop following functionality for a sidebar. In a nutshell, Sidebar will have 100% height and will be absolutely positioned. Inside it there is content, which should scroll with the page, while sidebar is fixed. And as addition there is a shadow effect / response to show user if he can scroll down or up. So for example if there is something that can be scrolled down / up show shadow there, if not don't show shadow. I made a quick mockup, hopefully it will help you understand what happens if page is scrolled:
I made a quick jsfidle with content and sidebar, this is as far as I can get at the moment. http://jsfiddle.net/cJGVJ/3/
I assume this can't be achieved only with css and html and work cross browser, so jQuery solutions are welcome.
HTML
<div id="main"> <!-- Demo Content (Scroll down for sidebar) -->
<!-- Demo content here -->
</div>
<aside id="sidebar">
<div id="side-content-1"></div>
<div id="side-content-2"></div>
</aside>
CSS
body {
background: #f3f3f3;
margin: 0;
padding: 0;
}
#page-wrapper {
width: 90%;
margin: 0 auto;
overflow: hidden;
}
#sidebar {
width: 30%;
float: left;
background: #ffffff;
padding: 10px;
height: 100%;
position: fixed;
}
#main {
width: 60%;
float: right;
}
#side-content-1, #side-content-2 {
height: 400px;
}
#side-content-1 {
background: red;
opacity: 0.4;
}
#side-content-2 {
background: green;
opacity: 0.4;
margin-top: 10px;
}
EDIT
Bare in mind content in sidebar sums up to less than one of the page content, so once it reaches the bottom (so when bottom shadow disappears) it should stay there, while main content can be still scrolled down.
This is still a little rough, but its a start:
I went through and polished it a little more and took care of some window resizing issues.
I think this will work for you:
Updated Working Example
JS
$(window).scroll(function () {
var y = $(window).scrollTop();
var x = $(window).scrollTop() + $(window).height();
var s = $('#sidebar').height();
var o = $('#side-content-1').offset().top;
var q = $('#side-content-1').offset().top + $('#side-content-1').height();
var u = $('#side-content-2').offset().top;
if (x > s) {
$('#sidebar').css({
'position': 'fixed',
'bottom': '0',
'width': '27%'
});
$('#bottomShadow').hide();
}
if (x < s) {
$('#sidebar').css({
'position': 'static',
'width': '30%'
});
$('#bottomShadow').show();
}
if (y > o) {
$('#topShadow').show().css({
'position': 'fixed',
'top': '-2px'
});
}
if (y < o) {
$('#topShadow').hide();
}
if (y > q - 4 && y < q + 10) {
$('#topShadow').hide();
}
if (x > u - 10 && x < u + 4) {
$('#bottomShadow').hide();
}
});
var shadow = (function () {
$('#topShadow, #bottomShadow').width($('#sidebar').width());
});
$(window).resize(shadow);
$(document).ready(shadow);
CSS
body {
background: #f3f3f3;
margin: 0;
padding: 0;
}
#page-wrapper {
width: 90%;
margin: 0 auto;
overflow: hidden;
}
#sidebar {
width: 30%;
float:left;
background: #ffffff;
padding: 10px;
}
#main {
width: 60%;
float: right;
}
#side-content-1, #side-content-2 {
height: 400px;
}
#side-content-1 {
background: red;
opacity: 0.4;
}
#side-content-2 {
background: green;
opacity: 0.4;
margin-top: 10px;
}
#topShadow {
display:none;
height:2px;
box-shadow:0px 5px 4px #000;
}
#bottomShadow {
position:fixed;
bottom:-3px;
height:2px;
width:99%;
box-shadow:0px -5px 4px #000;
}
CSS Tricks website have an article on Persistent Headers where they accomplish something similar with a bit of JQuery

Categories

Resources