How does Google make its scrollbars? - javascript

I was just on http://www.google.com/finance and noticed on the middle of the page an awesome looking scrollbar.
How does Google create this scrollbar look/feel?
Note: this scrollbar is different than what Google used with it's Wave product.
Screenshot
UPDATE:
The scrollbar doesn't appear immediately. Do NOT refresh the page. Let the page sit ideal for a few moments until there is new news story in the world. Once a new news story appears, the new article will cause the scrollbar to appear.

Very interesting question. I just had spare time and spent it to implement simple example of this (spent about 1 hour with a cup of tea with candies ;)). Look at this:
<script src='jquery.js'></script>
<script src='jquery-ui.js'></script>
<style>
.frame {
position: relative;
top: 150px;
left: 150px;
width: 500px;
height: 500px;
overflow: hidden;
border: 1px solid black;
}
.frame > div {
border: 1px solid black;
}
.frame .content {
margin-right: 0px;
height: 498px;
overflow: hidden;
}
.frame .scrollbar {
float: right;
width: 20px;
text-align: center;
}
.frame .scrollbar .scroller {
position: relative;
border-right: 1px solid black;
width: 10px;
height: 91.8%;
}
.frame .scrollbar .scroll-up, .frame .scrollbar .scroll-down {
cursor: pointer;
}
.frame .scrollbar .scroll-up:hover, .frame .scrollbar .scroll-down:hover {
background: blue;
color: White;
}
.frame .scroller-draggable {
background: #EEF1F7;
border: 1px solid #D5DFF3;
height: 20px;
margin-left: 1px;
margin-right: -10px;
cursor: pointer;
}
</style>
<div class="frame">
<div class="scrollbar">
<div class="scroll-up">[^]</div>
<div class="scroller">
<div class="scroller-draggable"></div>
</div>
<div class="scroll-down">[v]</div>
</div>
<div class="content">
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Integer enim elit, tristique id tristique sed, vulputate eu libero. Nam nec lectus orci, at varius est. Aenean quis velit a lorem bibendum dignissim eu ac ipsum. Vestibulum convallis diam faucibus dolor placerat sed iaculis sapien mattis. Maecenas in velit nec mauris aliquam condimentum. Mauris porttitor magna id est ultrices dapibus. Fusce at urna felis. Quisque congue dignissim bibendum. Praesent egestas elementum ante, non condimentum libero tempor quis. Nullam fermentum tincidunt aliquam. Suspendisse nec mi velit. Nulla facilisi. Etiam vitae sem nec orci feugiat mattis a quis massa. Vivamus rutrum suscipit tempor. Proin varius interdum arcu eget auctor. Vivamus quis placerat nulla. Praesent imperdiet tempus dictum. Donec pharetra, orci ac gravida euismod, sapien tellus feugiat velit, eu egestas nunc nisi at enim. Phasellus blandit placerat neque, non rhoncus tellus commodo sit amet. Donec lectus erat, ornare sit amet venenatis id, viverra ac quam.</p>
<p>Sed aliquet metus vitae urna vulputate in mattis orci accumsan. Quisque dictum odio ac massa aliquet porttitor. Donec accumsan tortor sit amet ante vulputate at ullamcorper arcu auctor. Aenean gravida venenatis interdum. Aliquam erat volutpat. Integer eget dui vitae eros iaculis pharetra. In aliquam volutpat tincidunt. Sed vel imperdiet eros. Ut est nunc, venenatis sed varius et, scelerisque quis mi. Nullam aliquam pretium luctus. In hac habitasse platea dictumst. Etiam nec nibh libero. Nam pellentesque accumsan justo eget gravida. Ut egestas, mauris vitae egestas convallis, nibh turpis gravida justo, sit amet tincidunt libero orci eget metus.</p>
<p>Praesent convallis pellentesque tristique. Etiam vulputate, arcu sit amet dignissim feugiat, risus nulla adipiscing lectus, in dignissim metus mi iaculis sem. Duis pulvinar vehicula leo nec porta. Cras nisl felis, elementum sit amet commodo sit amet, gravida quis augue. Praesent pretium sapien ut orci rutrum auctor. Aliquam erat volutpat. Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Sed porta mattis cursus. Duis facilisis enim quam, quis imperdiet nulla. Mauris dapibus tincidunt felis vel ultrices. Fusce ut diam lectus. In lacinia ultrices leo, ut fringilla tellus egestas eget. Ut in odio et est tristique tempor quis a orci. Integer sodales adipiscing condimentum. Ut lacinia vehicula tellus sed feugiat. Sed libero libero, vestibulum ut pharetra nec, vestibulum vel augue. Aliquam consequat nibh id nulla porta porta.</p>
<p>Nullam ligula tortor, sollicitudin et sollicitudin a, vestibulum vel dui. Ut at facilisis nisi. Duis id ante quis augue iaculis congue. Nulla facilisi. Phasellus tincidunt condimentum nisi, ac ultricies augue ultricies et. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Donec id mauris a sapien suscipit adipiscing. Pellentesque accumsan pulvinar tortor et elementum. Nulla facilisi. Nulla tempor lectus et purus luctus ultricies. Phasellus aliquam, libero non ullamcorper vulputate, est lectus ultricies massa, vel tempus magna elit ac lacus. Sed id dui purus. Quisque vel erat ipsum. In in lectus diam, a tempor velit.</p>
<p>Duis tincidunt neque quis ipsum feugiat malesuada. Sed et tortor vel nunc porta commodo. Mauris lacinia suscipit sagittis. Praesent non nibh ac elit congue sagittis vitae non dui. Nunc risus urna, sodales faucibus rhoncus at, interdum faucibus velit. Vivamus ultrices neque vehicula turpis luctus non fringilla orci aliquam. Maecenas commodo, est vitae consequat scelerisque, metus sem malesuada dolor, non tincidunt nunc turpis non arcu. Donec rutrum mi nec neque dignissim ac gravida neque dignissim. Quisque porttitor elit a ante ultrices interdum. In tempor neque vitae tellus laoreet tincidunt. Pellentesque bibendum accumsan sapien suscipit vestibulum. Nullam justo libero, consectetur id rhoncus at, vulputate eu tortor. Suspendisse mattis, erat sed viverra malesuada, sapien leo interdum leo, in adipiscing nibh purus quis diam. Sed vitae convallis purus. Maecenas leo mauris, egestas ut vehicula vel, sodales non justo. In consequat scelerisque velit, id pharetra arcu fringilla eget.</p>
<p>Phasellus convallis porta velit at tempor. Etiam non quam tortor. Vivamus eget nulla turpis. Suspendisse potenti. Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Cras sollicitudin arcu quis libero tristique vel tempus turpis eleifend. Fusce sed justo sed sem tempor mattis vel eu nulla. Phasellus hendrerit tellus et dui luctus fermentum. Class aptent taciti sociosqu ad litora torquent per conubia nostra, per inceptos himenaeos. Maecenas ullamcorper, dolor eu egestas tincidunt, velit nulla sollicitudin metus, a ultrices nunc diam eu ante. Suspendisse sit amet hendrerit ante. Proin viverra posuere dolor. Nullam blandit lacus quis tortor dignissim non hendrerit risus pharetra.</p>
</div>
</div>
<script type="text/javascript">
$(function () {
$(".frame .scrollbar").find(".scroll-up, .scroll-down").click(function () {
var $content = $(this).closest(".frame").children(".content");
var dir = $(this).is(".scroll-up") ? -20 : 20;
$content.scrollTop($content.scrollTop() + dir);
});
$(".frame .content")
.bind("mousewheel", function (e) {
$(this).scrollTop($(this).scrollTop() - e.wheelDelta);
})
.scroll(function (e) {
var $scroller = $(this).closest(".frame").children(".scrollbar").children(".scroller");
var $scrollerDraggable = $scroller.children(".scroller-draggable");
if ($scrollerDraggable.data("isscrolling"))
return;
var pos = $(this).scrollTop() / ($(this)[0].scrollHeight - $(this).height());
console.log([pos]);
$scrollerDraggable.css("top", ($scroller.height() - $scrollerDraggable.height()) * pos);
})
$(".frame .scroller-draggable").draggable({
axis: 'y',
containment: $(".frame .scroller"),
start: function () {
$(this).data("isscrolling", true);
},
drag: function (event, ui) {
var $scroller = $(this).closest(".scroller");
var $content = $scroller.closest(".frame").children(".content");
var pos = ui.position.top / ($scroller.height() - $(this).height());
$content.scrollTop(($content[0].scrollHeight - $content.height()) * pos);
},
stop: function () {
$(this).data("isscrolling", false);
}
});
});
</script>
It requires JQuery and Jquery UI, and the example still has some issues, but main idea is realized. Example tested ONLY in Chrome 7.
You can make a jquery plugin from it.

Not that I can see it, but I imagine a custom control made out of various images.
You make a track image that tiles to make up the background, top and bottom cap images to act as the forward/back buttons (with hover and depressed states) and the moveable control is usually three-part, two end-caps on either side of a tileable central area that can be resized to suit. Then you monitor drags on the control area and keep it bound within the track, and clicks (or better mousedown) on the forward/back buttons.
There are libraries like jQuery UI Slider that handle this for you if you do not wish to code it yourself.

Although others have indicated how this is done (and that was the question, thus they are the "correct" answer) I'd like to suggest an alternative answer...
Seriously consider why you would want to do this
A scrollbar would be just as easy to add by setting 2 css properties (e.g. no code required)
.container{
height:200px;/*some fixed height*/
overflow-y:auto;/*adds a native scrollbar, only when needed*/
}
The problem with the custom scrollbar is that it doesn't behave quite like a native one does.
You can't click on the track to scroll the content
You can't use the scroll-wheel on your mouse to scroll the content
You can't use the up/down arrow keys, home, end,page up, page dn to scroll the content
The thumbscrew doesn't change in size to reflect the amount of content that can be scrolled
These may not seem like a major issue, but changing/removing the "behavior" of UI controls that users are used to is generally not advised.
Quote from Jakob Neilsen's Usability site "Alertbox" article: "Scrolling and Scrollbars" - July 11, 2005. (emphasis mine)
Scrollbars are easy to get right. In fact, the less work you do, the better your scrollbar. Usability is almost always enhanced when you use the built-in scrollbars rather than design your own.

Related

How can I make my sidebar fixed after a certain size?

I see this sample:
link
If you do come down ... you see the sidebar on the right becomes fixed after a certain size ... you actually get down to almost everything.
How it was made an event the example?
With JQuery?
This is the link to my site
I tried to do something similar but incomplete
CODE JS:
$(window).scroll(function() {
var height = $(window).scrollTop();
console.log(height);
if(height > 700) {
//alert("test");
//after a certain size should be fixed ... what code should be here?
}
});
Did you have any idea as an example?
Can you help me solve this problem please?
Thanks in advance!
Here the example of not smooth scrolling of div.
(function($) {
var element = $('.follow-scroll'),
originalY = element.offset().top;
// Space between element and top of screen (when scrolling)
var topMargin = 20;
// Should probably be set in CSS; but here just for emphasis
element.css('position', 'relative');
$(window).on('scroll', function(event) {
var scrollTop = $(window).scrollTop();
element.stop(false, false).animate({
top: scrollTop < originalY
? 0
: scrollTop - originalY + topMargin
}, 0);
});
})(jQuery);
html { box-sizing: border-box; }
*, *:before, *:after { box-sizing: inherit; }
.group:after { content: ""; display: table; clear: both; }
body { font: 15px/20px sans-serif; color: #444; }
p { margin-bottom: 30px; }
.wrapper { width: 100%; max-width: 700px; padding: 3%; }
.content, .sidebar { float: left; }
.content { width: 68%; margin-right: 5%; }
.sidebar { width: 27%; }
.box { background: #eee; border: 1px solid #ccc; padding: 10px; margin-bottom: 20px; }
<div class="wrapper group">
<div class="content">
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Etiam euismod arcu ut diam maximus auctor. Sed malesuada maximus tellus, dignissim volutpat urna hendrerit at. Cras nisi turpis, mattis vitae ornare ut, bibendum et massa. Nulla at tellus a arcu luctus ultrices ac non felis. Maecenas euismod efficitur ipsum vel vestibulum. Nam imperdiet ipsum nunc, sit amet varius felis maximus quis. Etiam efficitur, mauris placerat luctus facilisis, ligula sem pellentesque nunc, ac viverra tellus velit sit amet purus. Proin a nunc id quam tempor blandit vitae id orci. Cras lectus turpis, varius nec elementum venenatis, suscipit ut nisl.</p>
<p>Nulla condimentum est in leo mollis, sit amet varius erat pulvinar. Donec posuere turpis non est ultrices lobortis. Donec commodo aliquam sodales. Ut id finibus velit. Aenean tempus eget nulla at condimentum. Ut a arcu quis dui ultricies efficitur. Vestibulum suscipit diam ullamcorper velit tempor, in ullamcorper odio sollicitudin. Vestibulum congue nisl nibh, ut elementum quam tristique non. Nulla in sollicitudin dolor. Morbi ac justo nulla. Suspendisse massa neque, vestibulum id dolor non, congue rhoncus nibh.</p>
<p>Phasellus porta tellus vel ipsum vehicula, nec fermentum lectus porta. Aenean viverra magna eu risus lacinia malesuada. Sed molestie auctor pharetra. Aliquam erat volutpat. Vestibulum in mi a orci tincidunt pellentesque. Sed et lectus eros. Nam imperdiet neque eu dolor gravida, interdum pellentesque justo rhoncus. Morbi tincidunt, ex nec pellentesque pulvinar, dui nulla tempor ipsum, sed consequat est tortor at neque. Suspendisse sed consequat urna. Nullam luctus, sem convallis volutpat mollis, sapien odio finibus elit, vitae fringilla enim leo sed velit. Vivamus fringilla ante laoreet blandit porta. Sed condimentum ut erat nec dignissim.</p>
<p>Morbi ac scelerisque metus. Donec rhoncus diam urna, nec aliquet ex mollis ut. Sed a arcu ac risus semper pellentesque ut non nibh. Phasellus eu ullamcorper sem. Maecenas at tortor faucibus, consequat risus sed, egestas sapien. Suspendisse tortor lacus, congue sed velit vel, dictum sagittis eros. Proin eu nisl viverra, mattis velit vitae, tempor turpis. Ut sodales lacus in iaculis faucibus. Integer non metus non nulla malesuada rutrum ac non ipsum. Vivamus quam diam, suscipit sed velit vel, tincidunt imperdiet urna. Praesent dapibus augue a dignissim lacinia. Nullam pharetra volutpat ligula, quis aliquet mauris pharetra nec. Etiam finibus, neque in laoreet vehicula, lorem justo feugiat velit, ac accumsan neque lacus non tellus. Aliquam quis sagittis massa, a bibendum enim.</p>
<p>Morbi vel elementum libero, vitae viverra est. Pellentesque sollicitudin neque at ligula suscipit, vel faucibus mauris consequat. Donec quis pharetra nulla, at tristique lacus. Nunc vel magna ultricies, hendrerit purus et, rhoncus dolor. Aliquam erat volutpat. Phasellus auctor malesuada augue, a iaculis sem mattis quis. Nulla facilisi.</p>
</div>
<div class="sidebar">
<div class="box">
First box
</div>
<div class="box">
Second box
</div>
<div class="box follow-scroll">
Third box (follows screen)
</div>
</div>
</div>

How can I fadeOut a div when I scroll down to the hole div, It will not show again

I am looking to implement a feature in which a notification displays via slideDown at the top of the page on a button (or other element) click, and then hides via fadeOut when it is scrolled out of view. This functionality is similar to what happens when clicking "How It Works" on airbnb's website.
For clarity, the following is the functionality that I am looking for:
Click a specified element to make the notification display
Notification slides into view at the top of the page and window automatically scrolls to the top
User scrolls down the page and the notification element fades out as soon as it is scrolled out of view
Does anyone have any idea how this can be implemented?
The implementation they use is pretty long and has a lot of functions returning functions, but the following is a quick pseudo-code description of what you need to do:
Create a click handler for the element you want to use as your "show button" that shows your "notification" when clicked. Note that my implementation jumps to the top of the page. In your implementation, you should change this to the smooth scrolling technique of your choice. UPDATE: I checked against Airbnb's site again and even without the smooth scrolling my implementation visually functions the same as theirs.
var $notification = $(".notification");
$(document).on("click", ".show-button", function() {
$notification.slideDown(); //can use whatever effect you want here, or just .show()
window.scrollTo(0, 0); //scroll to top of page
});
Next, create a scroll handler for the window that checks to see if the page has been scrolled down below the height of the "notification" (in other words, check to see if the notification is no longer in view). If it is not in view anymore, hide the element and update the scroll position so the page doesn't jump. Note that with my implementation, the page may jump in slower browsers because I'm not using smooth scrolling. However, when you add smooth scrolling the effect will look natural.
$(window).on("scroll", function() {
var notificationHeight = $notification.outerHeight(); //may be able to cache this or calculate outside the handler for reuse, depending on implementation
var currentScrollY = $(window).scrollTop();
if (currentScrollY > notificationHeight) {
$notification.hide();
//update the scroll browser scroll position
var updatedScrollY = currentScrollY - notificationHeight;
window.scrollTo(window.scrollX, updatedScrollY);
}
});
If we are looking to use an animation/effect to hide the "notification," then we need to update our scroll handler from the above. Looking at the current code, notice that we use $notification.hide() which instantly removes the element from the document. As such, the space consumed by the notification is not included when we compute the updated scroll position. However, if you use an animation/effect, like .fadeOut, the element's display property is not set to none until the animation COMPLETES, though the script execution continues immediately after the animation BEGINS (i.e. immediately after it is called). As such, the new scroll position will be calculated and applied before the notification is removed from the flow, causing the page to appear to jump to the top, with the notification in full or nearly full view. In order to get around this, we need to hold off on the execution of the the code to update the scroll position until the animation/effect finishes. We can do this easily moving the code for updating the scroll position into the animation/effect method's callback.
$(window).on("scroll", function() {
var notificationHeight = $notification.outerHeight(); //may be able to cache this or calculate outside the handler for reuse, depending on implementation
var currentScrollY = $(window).scrollTop();
if (currentScrollY > notificationHeight) {
//can use whatever effect you want, but must pass scroll position update code in callback to prevent page jump, if not using .hide()
$notification.fadeOut(function () {
//update the scroll browser scroll position
var updatedScrollY = currentScrollY - notificationHeight;
window.scrollTo(window.scrollX, updatedScrollY);
});
}
});
NOTE: Since we cannot see the element, we shouldn't be using an animation/effect, like fadeOut, to hide the notification. Adding the effect would merely add unnecessary overhead, since the element is not in view when it is hidden. However, I have included this step because the OP specifically mentioned using fadeOut for hiding the notification. I will include examples for both in the demo.
Since I'm a fan of performance and we don't need handle the scroll event of window unless the "notification" is actually being shown, let's move our scroll handler binding into a function, and add a namespace and .off call so that we can unbind it without affecting other handlers.
//binds the scroll handler we created in step 2 to the window
function bindScrollHandlerForNotification() {
$(window).on("scroll.checkHideNotification", function() {
var notificationHeight = $notification.outerHeight(); //may be able to cache this or calculate outside the handler for reuse, depending on implementation
var currentScrollY = $(window).scrollTop();
if (currentScrollY > notificationHeight) {
//can use whatever effect you want, but must pass scroll position update code in callback to prevent page jump, if not using .hide()
$notification.fadeOut(function() {
//update the scroll browser scroll position
var updatedScrollY = currentScrollY - notificationHeight;
window.scrollTo(window.scrollX, updatedScrollY);
//unbind the handler since the notification is hidden
$(window).off("scroll.checkHideNotification");
});
}
});
}
Now that we have a function to bind our handler, let's update the click handler from step 1 to call the function to bind our scroll handler.
$(document).on("click", ".show-button", function() {
$notification.slideDown(); //can use whatever effect you want here, or just .show()
window.scrollTo(0, 0); //scroll to top of page
bindScrollHandlerForNotification();
});
FINAL IMPLEMENTATIONS AND DEMOS
Using .fadeOut() to hide notification
var $notification = $(".notification");
//listen for our show button to be clicked
$(document).on("click", ".show-button", function() {
$notification.slideDown(); //can use whatever effect you want here, or just .show()
window.scrollTo(0, 0); //scroll to top of page
bindScrollHandlerForNotification();
});
//binds the scroll handler we created in step 2 to the window
function bindScrollHandlerForNotification() {
$(window).on("scroll.checkHideNotification", function() {
var notificationHeight = $notification.outerHeight(); //may be able to cache this or calculate outside the handler for reuse, depending on implementation
var currentScrollY = $(window).scrollTop();
if (currentScrollY > notificationHeight) {
//can use whatever effect you want, but must pass scroll position update code in callback to prevent page jump, if not using .hide()
$notification.fadeOut(function() {
//update the scroll browser scroll position
var updatedScrollY = currentScrollY - notificationHeight;
window.scrollTo(window.scrollX, updatedScrollY);
//unbind the handler since the notification is hidden
$(window).off("scroll.checkHideNotification");
});
}
});
};
.page-container {
height: 5000px;
}
.notification {
display: none;
padding: 75px;
border-bottom: 1px solid white;
background: #009afd;
text-align: center;
font-size: 30px;
font-weight: bold;
font-family: arial, helvetica, sans-serif;
}
.main-content {
width: 75%;
height: 100%;
margin: 0 auto;
border-left: 2px solid rgb(200, 200, 200);
border-right: 2px solid rgb(200, 200, 200);
padding: 20px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div class="page-container">
<div class="notification"><span class="notification-content">Test Notification</span>
</div>
<div class="main-content">
<div class="content-block">
<button type="button" class="show-button">Show Notification</button>
</div>
</div>
</div>
Using .hide() to hide notification
var $notification = $(".notification");
//listen for our show button to be clicked
$(document).on("click", ".show-button", function() {
$notification.slideDown(); //can use whatever effect you want here, or just .show()
window.scrollTo(0, 0); //scroll to top of page
bindScrollHandlerForNotification();
});
//binds the scroll handler we created in step 2 to the window
function bindScrollHandlerForNotification() {
$(window).on("scroll.checkHideNotification", function() {
var notificationHeight = $notification.outerHeight(); //may be able to cache this or calculate outside the handler for reuse, depending on implementation
var currentScrollY = $(window).scrollTop();
if (currentScrollY > notificationHeight) {
//can use whatever effect you want, but must pass scroll position update code in callback to prevent page jump, if not using .hide()
$notification.hide();
//update the scroll browser scroll position
var updatedScrollY = currentScrollY - notificationHeight;
window.scrollTo(window.scrollX, updatedScrollY);
//unbind the handler since the notification is hidden
$(window).off("scroll.checkHideNotification");
}
});
};
.page-container {
height: 5000px;
}
.notification {
display: none;
padding: 75px;
border-bottom: 1px solid white;
background: #009afd;
text-align: center;
font-size: 30px;
font-weight: bold;
font-family: arial, helvetica, sans-serif;
}
.main-content {
width: 75%;
height: 100%;
margin: 0 auto;
border-left: 2px solid rgb(200, 200, 200);
border-right: 2px solid rgb(200, 200, 200);
padding: 20px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div class="page-container">
<div class="notification"><span class="notification-content">Test Notification</span>
</div>
<div class="main-content">
<div class="content-block">
<button type="button" class="show-button">Show Notification</button>
</div>
</div>
</div>
Sorry for the messy code, but it gets the point across.
$(document).ready(function() {
$("#slideDiv").click(function() {
$("#banner").show().animate({height: "300px"}, 0);
});
$(window).scroll(function (event) {
var scroll = $(window).scrollTop();
var link = $("#banner");
var offset = link.offset();
var top = offset.top;
var bottom = top + link.outerHeight();
if(scroll > bottom) {
link.hide().css({height: 0});
window.scrollTo(0, 0);
}
});
});
#banner {
height: 0px;
width: 100%;
display: inline-block;
background: #eee;
transition: height 0.5s;
}
<!DOCTYPE html>
<html>
<head>
<script src="//cdnjs.cloudflare.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
</head>
<body>
<div id="banner">
</div>
test
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Maecenas blandit sapien quis augue blandit faucibus. Nullam ac purus cursus turpis tempus blandit. Maecenas quis diam turpis. Integer metus ligula, pulvinar nec arcu et, tempor lobortis nunc. Integer in nunc in mi bibendum bibendum. Sed consectetur congue nibh id egestas. Quisque maximus, eros vitae mattis tempus, magna sem varius turpis, non accumsan ex velit nec mauris. Duis cursus commodo mi commodo facilisis. Donec turpis ante, gravida aliquet molestie porttitor, semper nec dolor.
Maecenas sed porta dui. Quisque vulputate tortor sed varius maximus. Ut eget mi eleifend, finibus ligula vel, malesuada diam. Etiam ultrices magna vitae condimentum sagittis. Maecenas tempor pellentesque lectus, eget ultricies ante maximus vestibulum. Phasellus molestie placerat dolor sit amet fringilla. In elit enim, vulputate quis varius eu, egestas nec nulla. Nulla congue eros vel nibh molestie sagittis. Mauris faucibus tellus at justo porta tincidunt. Vestibulum convallis ex et sapien placerat finibus. Nulla aliquam luctus tortor at dapibus. Phasellus semper orci eget magna egestas laoreet. Maecenas ut ligula egestas, lobortis enim efficitur, sollicitudin odio.
Phasellus porttitor mauris ut erat commodo, at bibendum massa ullamcorper. Nunc facilisis est eget sagittis gravida. Nulla eget augue semper, accumsan leo ac, sollicitudin tortor. In mi tortor, porta ac libero pretium, mollis fringilla massa. Maecenas auctor nibh ligula, vel varius nisl porta eget. Cras consectetur aliquet commodo. Aenean in tincidunt augue, non finibus mauris. Pellentesque rhoncus iaculis leo. Integer pellentesque tellus at tincidunt bibendum. Nullam vehicula pretium malesuada. Praesent in nulla posuere, auctor risus sed, volutpat ligula.
Nunc consectetur at ante eu pharetra. Nullam at augue hendrerit, laoreet erat vitae, maximus massa. Donec purus felis, varius lacinia ex vel, gravida aliquet arcu. Phasellus a ipsum nec odio convallis porttitor. Phasellus molestie lorem at aliquam sagittis. Aliquam sed ultricies nunc. Pellentesque vitae tincidunt ante, sit amet condimentum felis. Proin imperdiet, tellus eu vehicula interdum, libero augue sagittis nibh, in luctus neque turpis ac enim. Fusce iaculis semper lacus, non condimentum neque cursus in. Suspendisse rhoncus lectus eleifend purus consectetur, eu placerat felis tempus. Fusce turpis tortor, scelerisque ullamcorper tellus ac, iaculis viverra risus. Aenean varius mollis nisi, at euismod tellus. Integer ullamcorper ipsum eget nisi rhoncus finibus. Quisque eget commodo ex, pretium vehicula dui. Integer sed feugiat tellus. In hac habitasse platea dictumst.
Nunc risus elit, rutrum ac nisi in, gravida vestibulum nunc. Duis sodales blandit nisl, in condimentum nisi facilisis at. Nulla eleifend pulvinar libero, et congue sem molestie ut. Sed sollicitudin, neque quis iaculis vehicula, sapien dolor ornare nibh, nec placerat diam dui a leo. Nullam ut semper eros. Etiam vitae quam consequat, molestie ligula id, tincidunt ipsum. Proin ullamcorper malesuada faucibus. Nunc molestie in neque quis ultricies. Proin non diam non sapien tristique viverra.
Aenean sagittis metus eget mi ullamcorper accumsan. Maecenas in ex at arcu porta pellentesque gravida ut arcu. Nulla mattis sagittis erat eu pulvinar. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Donec rhoncus metus vel nulla eleifend, eu lacinia augue aliquam. Fusce id nisi quis tortor ultrices egestas non gravida dui. Aliquam volutpat aliquam felis, ac commodo felis venenatis nec. Duis interdum, est a sollicitudin commodo, turpis mauris consectetur nunc, ut eleifend quam ex ut ex. Phasellus et diam eget turpis placerat egestas vehicula at nibh. Phasellus feugiat nulla ac nisi vestibulum, a aliquet metus dictum. Vestibulum nec sapien vitae leo mollis ultrices ac sed sem.
Pellentesque vitae tincidunt ante, sit amet condimentum felis. Proin imperdiet, tellus eu vehicula interdum, libero augue sagittis nibh, in luctus neque turpis ac enim. Fusce iaculis semper lacus, non condimentum neque cursus in. Suspendisse rhoncus lectus eleifend purus consectetur, eu placerat felis tempus. Fusce turpis tortor, scelerisque ullamcorper tellus ac, iaculis viverra risus. Aenean varius mollis nisi, at euismod tellus. Integer ullamcorper ipsum eget nisi rhoncus finibus. Quisque eget commodo ex, pretium vehicula dui. Integer sed feugiat tellus. In hac habitasse platea dictumst. Nunc risus elit, rutrum ac nisi in, gravida vestibulum nunc. Duis sodales blandit nisl, in condimentum nisi facilisis at. Nulla eleifend pulvinar libero, et congue sem molestie ut. Sed sollicitudin, neque quis iaculis vehicula, sapien dolor ornare nibh, nec placerat diam dui a leo. Nullam ut semper eros. Etiam vitae quam consequat, molestie ligula id, tincidunt ipsum. Proin ullamcorper malesuada faucibus. Nunc molestie in neque quis ultricies. Proin non diam non sapien tristique viverra. Aenean sagittis metus eget mi ullamcorper accumsan. Maecenas in ex at arcu porta pellentesque gravida ut arcu. Nulla mattis sagittis erat eu pulvinar. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Donec rhoncus metus vel nulla eleifend, eu lacinia augue aliquam. Fusce id nisi quis tortor ultrices egestas non gravida dui. Aliquam volutpat aliquam felis, ac commodo felis venenatis nec. Duis interdum, est a sollicitudin commodo, turpis mauris consectetur nunc, ut eleifend quam ex ut ex. Phasellus et diam eget turpis placerat egestas vehicula at nibh. Phasellus feugiat nulla ac nisi vestibulum, a aliquet metus dictum. Vestibulum nec sapien vitae leo mollis ultrices ac sed sem.
Pellentesque vitae tincidunt ante, sit amet condimentum felis. Proin imperdiet, tellus eu vehicula interdum, libero augue sagittis nibh, in luctus neque turpis ac enim. Fusce iaculis semper lacus, non condimentum neque cursus in. Suspendisse rhoncus lectus eleifend purus consectetur, eu placerat felis tempus. Fusce turpis tortor, scelerisque ullamcorper tellus ac, iaculis viverra risus. Aenean varius mollis nisi, at euismod tellus. Integer ullamcorper ipsum eget nisi rhoncus finibus. Quisque eget commodo ex, pretium vehicula dui. Integer sed feugiat tellus. In hac habitasse platea dictumst. Nunc risus elit, rutrum ac nisi in, gravida vestibulum nunc. Duis sodales blandit nisl, in condimentum nisi facilisis at. Nulla eleifend pulvinar libero, et congue sem molestie ut. Sed sollicitudin, neque quis iaculis vehicula, sapien dolor ornare nibh, nec placerat diam dui a leo. Nullam ut semper eros. Etiam vitae quam consequat, molestie ligula id, tincidunt ipsum. Proin ullamcorper malesuada faucibus. Nunc molestie in neque quis ultricies. Proin non diam non sapien tristique viverra. Aenean sagittis metus eget mi ullamcorper accumsan. Maecenas in ex at arcu porta pellentesque gravida ut arcu. Nulla mattis sagittis erat eu pulvinar. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Donec rhoncus metus vel nulla eleifend, eu lacinia augue aliquam. Fusce id nisi quis tortor ultrices egestas non gravida dui. Aliquam volutpat aliquam felis, ac commodo felis venenatis nec. Duis interdum, est a sollicitudin commodo, turpis mauris consectetur nunc, ut eleifend quam ex ut ex. Phasellus et diam eget turpis placerat egestas vehicula at nibh. Phasellus feugiat nulla ac nisi vestibulum, a aliquet metus dictum. Vestibulum nec sapien vitae leo mollis ultrices ac sed sem.
Pellentesque vitae tincidunt ante, sit amet condimentum felis. Proin imperdiet, tellus eu vehicula interdum, libero augue sagittis nibh, in luctus neque turpis ac enim. Fusce iaculis semper lacus, non condimentum neque cursus in. Suspendisse rhoncus lectus eleifend purus consectetur, eu placerat felis tempus. Fusce turpis tortor, scelerisque ullamcorper tellus ac, iaculis viverra risus. Aenean varius mollis nisi, at euismod tellus. Integer ullamcorper ipsum eget nisi rhoncus finibus. Quisque eget commodo ex, pretium vehicula dui. Integer sed feugiat tellus. In hac habitasse platea dictumst. Nunc risus elit, rutrum ac nisi in, gravida vestibulum nunc. Duis sodales blandit nisl, in condimentum nisi facilisis at. Nulla eleifend pulvinar libero, et congue sem molestie ut. Sed sollicitudin, neque quis iaculis vehicula, sapien dolor ornare nibh, nec placerat diam dui a leo. Nullam ut semper eros. Etiam vitae quam consequat, molestie ligula id, tincidunt ipsum. Proin ullamcorper malesuada faucibus. Nunc molestie in neque quis ultricies. Proin non diam non sapien tristique viverra. Aenean sagittis metus eget mi ullamcorper accumsan. Maecenas in ex at arcu porta pellentesque gravida ut arcu. Nulla mattis sagittis erat eu pulvinar. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Donec rhoncus metus vel nulla eleifend, eu lacinia augue aliquam. Fusce id nisi quis tortor ultrices egestas non gravida dui. Aliquam volutpat aliquam felis, ac commodo felis venenatis nec. Duis interdum, est a sollicitudin commodo, turpis mauris consectetur nunc, ut eleifend quam ex ut ex. Phasellus et diam eget turpis placerat egestas vehicula at nibh. Phasellus feugiat nulla ac nisi vestibulum, a aliquet metus dictum. Vestibulum nec sapien vitae leo mollis ultrices ac sed sem.</p>
</body>
</html>
The jQuery checks if the scrollbar y-position is greater than the y-position of the bottom of the expanded div.
EDIT: Modified it to make it smoother and used the internal SO snippet tool.
You can use libraries to do this such as jQuery.
With it, this is what you will need to do:
Create a 'click()' function to make your div slide down
Attach that function to some element (like a button in my example)
Create a 'scroll()' function to see when the scroll reaches a certain height
Make your div 'fadeOut()' when it does
JS
$("#clickme").click(function() {
$("#slideme").slideDown("slow");
});
$(document).scroll(function(){
if($(document).scrollTop()>100 /* Insert height here */){
$("#slideme").fadeOut();
}
});
You can find the JSFiddle here: http://jsfiddle.net/qrdttrL1/1/

jQuery UI tabs where the tabs and their contents fill 100% of the available space

I'm struggling with this seemingly easy task: making jQuery UI tabs fill a window (100% height and width) while setting the tab content divs to fill the available space.
Here's what I'm dealing with: http://jsfiddle.net/rgw2raej/
In this example, the "red box" is much longer than the tab's available space even though it's set to 100% height. How can I get it to fill the tab's available space?
Here's the code (because Stack Overflow told me to):
HTML:
<div id="tabs">
<ul>
<li>Nunc tincidunt
</li>
<li>Proin dolor
</li>
<li>Aenean lacinia
</li>
</ul>
<div id="tabs-1">
<p>Proin elit arcu, rutrum commodo, vehicula tempus, commodo a, risus. Curabitur nec arcu. Donec sollicitudin mi sit amet mauris. Nam elementum quam ullamcorper ante. Etiam aliquet massa et lorem. Mauris dapibus lacus auctor risus. Aenean tempor ullamcorper leo. Vivamus sed magna quis ligula eleifend adipiscing. Duis orci. Aliquam sodales tortor vitae ipsum. Aliquam nulla. Duis aliquam molestie erat. Ut et mauris vel pede varius sollicitudin. Sed ut dolor nec orci tincidunt interdum. Phasellus ipsum. Nunc tristique tempus lectus.</p>
</div>
<div id="tabs-2">
<p>Morbi tincidunt, dui sit amet facilisis feugiat, odio metus gravida ante, ut pharetra massa metus id nunc. Duis scelerisque molestie turpis. Sed fringilla, massa eget luctus malesuada, metus eros molestie lectus, ut tempus eros massa ut dolor. Aenean aliquet fringilla sem. Suspendisse sed ligula in ligula suscipit aliquam. Praesent in eros vestibulum mi adipiscing adipiscing. Morbi facilisis. Curabitur ornare consequat nunc. Aenean vel metus. Ut posuere viverra nulla. Aliquam erat volutpat. Pellentesque convallis. Maecenas feugiat, tellus pellentesque pretium posuere, felis lorem euismod felis, eu ornare leo nisi vel felis. Mauris consectetur tortor et purus.</p>
</div>
<div id="tabs-3">
<p>Mauris eleifend est et turpis. Duis id erat. Suspendisse potenti. Aliquam vulputate, pede vel vehicula accumsan, mi neque rutrum erat, eu congue orci lorem eget lorem. Vestibulum non ante. Class aptent taciti sociosqu ad litora torquent per conubia nostra, per inceptos himenaeos. Fusce sodales. Quisque eu urna vel enim commodo pellentesque. Praesent eu risus hendrerit ligula tempus pretium. Curabitur lorem enim, pretium nec, feugiat nec, luctus a, lacus.</p>
<p>Duis cursus. Maecenas ligula eros, blandit nec, pharetra at, semper at, magna. Nullam ac lacus. Nulla facilisi. Praesent viverra justo vitae neque. Praesent blandit adipiscing velit. Suspendisse potenti. Donec mattis, pede vel pharetra blandit, magna ligula faucibus eros, id euismod lacus dolor eget odio. Nam scelerisque. Donec non libero sed nulla mattis commodo. Ut sagittis. Donec nisi lectus, feugiat porttitor, tempor ac, tempor vitae, pede. Aenean vehicula velit eu tellus interdum rutrum. Maecenas commodo. Pellentesque nec elit. Fusce in lacus. Vivamus a libero vitae lectus hendrerit hendrerit.</p>
</div>
</div>
CSS:
#tabs {
position: absolute;
top: 0;
right: 0;
bottom: 0;
left: 0;
}
#tabs-1, #tabs-2, #tabs-3 {
border: 5px solid red !important;
height: 100%;
}
JS:
$(function () {
$("#tabs").tabs();
});
This is a long-standing CSS bugbear, and there are some truly ugly solutions out there.
Finally, CSS3 delivers an elegant-ish solution. It's called 'flex'.
Remove the "height:100%" rules, and replace them with:
#tabs {
display:flex;
flex-direction:column;
flex:1;
}
#tabs-1, #tabs-2, #tabs-3 {
flex:1;
}
Here's your page with this code added: http://jsfiddle.net/bgxpc9y9/
Is that what you wanted?
Instead of using position: absolute on #tabs, use display: block.
Here is a working fiddle: http://jsfiddle.net/rgw2raej/1/

How Do I Limit Scrolling to a Fixed Div?

I have two divs, structured as follows:
<div id="container">
<div id="inner"></div>
</div>
The outer, container div has a very large height (this is simply meant to emulate a real-world scenario where there's a lot of content in the parent div). The inner div is a fixed position div, with a defined height. Overflow-y is set on the inner div, so that people can scroll through it to see any content that doesn't fit within its defined height.
Here's a codepen: http://codepen.io/anon/pen/myVxar
How do I set it such that when you're done scrolling through the inner div, the outer div does not scroll? In other words, scrolling within the inner div should never scroll the outer div.
Is there a way to do this using CSS/HTML? If not, how would I do it using Javascript/Jquery?
You can't disable the scroll for the page but you can disable the mousewheel event
Edit: I do have to say that if you are running into this in the real world and you have full control over the front end code you should rethink you're strategy, because there is most definitely a better way.
function preventDefault(e) {
e = e || window.event;
if (e.preventDefault)
e.preventDefault();
e.returnValue = false;
}
function wheel(e) {
preventDefault(e)
}
// bind some scroll functionality to the inner div
$('#inner').on('scroll', function(e){
var elem = $(e.currentTarget);
// check if user has scrolled to bottom
if (elem[0].scrollHeight - elem.scrollTop() == elem.outerHeight()){
// disable mouse scroll event
if (window.addEventListener) {
window.addEventListener('DOMMouseScroll', wheel, false);
}
window.onmousewheel = document.onmousewheel = wheel;
console.log('done')
} else{
// remove the event that disables scroll
if (window.removeEventListener) {
window.removeEventListener('DOMMouseScroll', wheel, false);
}
window.onmousewheel = document.onmousewheel = document.onkeydown = null;
}
});
// remove the event that disabled scroll if user mouse leaves inner container
$('#inner').mouseout(function(e){
if (window.removeEventListener) {
window.removeEventListener('DOMMouseScroll', wheel, false);
}
window.onmousewheel = document.onmousewheel = document.onkeydown = null;
})
Also wondering why you are taking this approach. I think you may be setting the large height in case the content is long, but why not just do something like this?
#container {
height:200px;
width:300px;
overflow:scroll;
border:1px solid;
}
Once the inner content overflows the container, the container will scroll - the .inner doesn't need any styling relating to the scrolling. Post more detail if I am missing something.
Assuming that the inner div isn't always covering other content... You could just adjust the height and overflow of the container when you show the inner div:
Working Example
$('#container').click(function () {
if ($('#inner').is(':visible')) {
$('#inner').fadeOut('slow');
$('#container').css({
height: 14000,
overflow: 'auto'
});
} else {
$('#inner').fadeIn('slow', function () {
$('#container').css({
height: "100%",
overflow: 'hidden'
});
});
}
});
#container {
height: 14000px;
width: 100%;
}
#inner {
display:none;
background: #fff;
position: fixed;
top: 0;
left: 0;
height: 100vh;
width: 100%;
overflow-y: scroll;
box-sizing: border-box;
padding: 15px;
font-size: 18px;
color: #808080;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="container">click Me!
<div id="inner">Lorem ipsum dolor sit amet, consectetur adipiscing elit. Aenean volutpat mauris at consequat rutrum. Nam ut tempus nisl, quis luctus turpis. In eu dolor a ligula rhoncus convallis a in lectus. Cras pretium felis in justo semper convallis. Integer nisl arcu, venenatis sed odio in, accumsan consectetur mi. Sed fermentum tempus elit at varius. Proin scelerisque auctor nibh quis lobortis. Aliquam enim elit, rhoncus at ultricies a, rutrum id ipsum. Morbi eu justo id mi accumsan ullamcorper at eget risus. Curabitur elementum ultrices ex, sit amet laoreet orci. Proin lobortis quis lacus quis tristique. Nulla facilisi. Quisque vel libero quis lectus convallis volutpat. Sed ullamcorper luctus neque, id efficitur eros fermentum id. Fusce et nulla faucibus, faucibus ante id, pellentesque erat. Quisque ac feugiat nisi, eget feugiat nulla. Morbi quis interdum tellus. Etiam porttitor lacus ac orci rhoncus, eu commodo lacus tempus. Aliquam finibus egestas leo eget efficitur. Duis maximus tincidunt lorem, eu convallis ipsum feugiat lobortis. Proin auctor volutpat velit, ac suscipit neque vestibulum sed. Suspendisse pretium, libero sit amet euismod imperdiet, risus nulla sodales mi, luctus imperdiet enim augue at odio. Suspendisse mollis, eros quis malesuada feugiat, mi libero elementum odio, eu scelerisque elit nibh quis ante. Sed malesuada porttitor dui in volutpat. Praesent consequat nisi vel ipsum bibendum, at mollis nibh congue. Cras vitae turpis aliquet, sollicitudin libero ut, fringilla ex. In leo sem, mollis et quam eget, cursus laoreet quam. Fusce pulvinar felis eu finibus venenatis. Integer quis mauris commodo, sollicitudin mi ullamcorper, hendrerit justo. Donec luctus ultrices ante. Curabitur eget neque eu augue mattis elementum a vel ante. Aliquam posuere augue ac velit bibendum, ut efficitur mi convallis. Curabitur velit tellus, facilisis vel elit at, ornare scelerisque massa. Donec rhoncus eget diam non tincidunt. Ut in sapien sapien. Mauris ultricies est ut facilisis mollis. Duis finibus malesuada mollis. Praesent ultricies lectus sed dolor pellentesque, ac volutpat ipsum maximus. Donec risus nulla, accumsan vel orci sit amet, tristique rhoncus diam. Praesent malesuada tincidunt placerat. Proin at congue odio. Sed ac velit quis risus aliquet consectetur at sit amet magna. Fusce quis lacinia elit, eget tincidunt libero. Donec ac elit vel lacus iaculis aliquet vitae ut purus. Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Donec condimentum mauris ipsum, at laoreet odio sodales at. Vestibulum in ex tellus. Proin non varius ligula, nec ultricies ligula. Praesent quis lacus at augue tristique faucibus. Quisque eleifend eu magna sed fermentum. Phasellus ac mattis erat. Donec pharetra nunc eget facilisis condimentum. Etiam sagittis tempus sapien, id malesuada felis pretium eu. Aenean hendrerit nec velit at euismod. Pellentesque at maximus risus, sed eleifend nisi. Sed quis interdum orci. Donec vel nisl malesuada, interdum felis at, porttitor odio.</div>
</div>

How can I make the sidebar stop at a specific div while the user scrolls down?

I'm using this code to make the sidebar fixed at a certain div while the user scrolls down. The problem is that I have to manually enter in a threshold number and this isn't always ideal since the position of the section may change or be inconsistent across various browsers and systems. I'm wondering if there is a way I can automatically have the sidebar become fixed once the user scrolls down and .Section2 hits the top.
Fiddle
http://jsfiddle.net/EvAdP/6/
HTML
<header>
I'm the header
</header>
<div id="container">
<aside id="sidebar">
<div class="section1">I'm a sidebar section</div>
<div class="Section2">I'm another sidebar section</div>
</aside>
<section id="content">
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Duis turpis turpis, dictum id sollicitudin eu, molestie ut tellus. Nam tincidunt mauris in erat vehicula adipiscing. Morbi cursus orci a nisl auctor nec porta eros consectetur. Vestibulum auctor congue mi, vitae molestie nisi faucibus vel. Ut et dui ut mauris posuere dignissim in et sapien. Duis a nulla ipsum. Duis accumsan porttitor justo at pretium. Aliquam quam urna, eleifend vitae consequat et, pharetra eu lectus. Etiam id magna mi. Donec pulvinar nibh in felis placerat condimentum consectetur enim iaculis. Integer et sapien justo, ac ullamcorper nisi. Praesent sed mauris non lacus pellentesque condimentum. Sed hendrerit consectetur nisi bibendum convallis. Pellentesque semper faucibus tortor malesuada dignissim.</p>
<p>Aliquam adipiscing commodo est, eu venenatis mi ullamcorper cursus. Integer vel magna in neque aliquet hendrerit. Mauris eros nisl, venenatis quis ultricies id, faucibus et mi. Nunc sit amet nulla odio. Phasellus quis eros id tortor imperdiet faucibus ac eu metus. Curabitur at feugiat dui. Vivamus imperdiet lectus id orci sodales sit amet eleifend ante tempus. Mauris vehicula elit eu dolor volutpat porttitor.</p>
<p>Praesent pretium convallis diam, sed faucibus dolor convallis eget. Pellentesque sollicitudin erat ac ligula viverra vel mollis diam tristique. Nulla tempus ligula ac dui fringilla consequat. Suspendisse accumsan volutpat semper. Morbi bibendum vehicula nibh id condimentum. Maecenas auctor mattis libero, ut suscipit tellus interdum quis. Nam eu dolor orci. Proin et tortor diam. Phasellus blandit leo ut elit faucibus varius. Donec condimentum congue lectus, sit amet gravida diam aliquet at.</p>
<p>Praesent eu libero sem. Phasellus elementum posuere velit, id aliquet ante elementum non. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Phasellus faucibus rutrum luctus. Suspendisse nec facilisis neque. Cras dui lacus, pellentesque at fermentum sollicitudin, aliquam et nisi. Proin eget sem diam, nec faucibus nulla. In nibh dolor, interdum at egestas a, dictum sed massa. Integer quis elit vitae enim lacinia tristique ac id purus. Pellentesque fermentum tempor sem sit amet venenatis. Nulla facilisi. Donec semper ultrices magna, posuere mattis turpis rhoncus ut.</p>
<p>Etiam porttitor erat sit amet odio egestas sit amet mollis magna convallis. Sed porttitor aliquet velit at placerat. Proin in turpis non velit gravida eleifend quis ac magna. Nunc sagittis, eros a pulvinar gravida, mauris urna viverra lorem, non posuere orci ligula vitae justo. Nulla neque erat, tempus at dapibus sit amet, scelerisque ac sapien. In in magna sapien, at auctor tellus. Donec nec turpis ligula, vitae scelerisque arcu.</p>
</section>
</div>
CSS
body {
margin:0;
}
header {
line-height:100px;
height:100px;
background-color:#F00;
}
#container {
position:relative;
}
#sidebar {
position:absolute;
background-color:#0F0;
}
#sidebar .section1 {
background: blue;
height: 150px;
width: 80px;
}
.Section2.fixed {
position:fixed;
top:0;
}
#sidebar .Section2 {
background: pink;
height: 150px;
width: 80px;
}
#sidebar.fixed {
position:fixed;
top:0;
}
#content {
margin-left:100px;
}
p:first-child {
margin-top:0;
}
JS
$(window).scroll(function () {
var threshold = 250;
if ($(window).scrollTop() >= threshold)
$('.Section2').addClass('fixed');
else
$('.Section2').removeClass('fixed');
});
Instead of specifying the threshold value try this
var threshold = $('.Section2').offset().top;
$(window).scroll(function () {
if ($(window).scrollTop() >= threshold)
$('.Section2').addClass('fixed');
else
$('.Section2').removeClass('fixed');
});
DEMO
Further to our discussions I thought I would post an alternative to the accepted solution that will work with flexible content.
It simply gets Section2 offset each time the scroll event is fired (but only if its not already .fixed):
EDIT: simply check that threshold is greater than zero:
var $Section2 = $('.Section2');
$(window).scroll(function () {
var threshold = $Section2.offset().top;
if (threshold>0 && $(window).scrollTop() >= threshold){
$Section2.addClass('fixed');
} else {
$Section2.removeClass('fixed');
}
});
DEMO

Categories