How Do I Limit Scrolling to a Fixed Div? - javascript

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>

Related

CSS/Javascript Challenge - Want to implement border bottom only for last line with centered text

I want to implement this layout for buttons on a project.
Things I have tried.
Recommendations from this Advanced CSS challenge: underline only the final line of text with CSS
but it only works for left aligned texts while I want to implement a text-align centered button.
The above post suggests:
a {
position: relative;
display: inline
}
a:after {
position: absolute;
left: 0;
bottom: 0;
width: 100%;
height: 1px;
border-bottom: 1px solid #000;
content: ""
}
Lorem Ipsum Foo Bar
Fiddle Try http://jsfiddle.net/VHdyf/88/
Underline only final line of text when centered This post is still open and suggests on duplicate content for this.
Any other ideas required.
This is meant to be responsive, so can't use a span inside just for the last line and give it a border.
Please help.
You can use JavaScript for this. This way you can use apply any CSS to your links and don't have to worry about it.
JavaScript algorithm of finding and highlighting words of last line:
Iterate through all links. Skip this step if you need to apply this style to only one element.
Get element's text (innerText).
Split text by whitespace (" ") sign.
Remove all elements from block.
Add spans with words and spans with whitespace (also save this spans to array).
Sort this array by span with the hightest top lowest left of span's rectangle to get first word of last line.
Get top element of this array.
Add highlighting class to the this element and its next siblings.
highlightLastLineForLinks();
// apply highlighting on window resize
window.addEventListener("resize", highlightLastLineForLinks);
// utility method to find all siblings
function getNextSiblings(elem, filter) {
var sibs = [];
while (elem = elem.nextSibling) {
if (!filter || filter(elem)) sibs.push(elem);
}
return sibs;
}
function highlightLastLineForLinks() {
var elements = document.querySelectorAll("a");
for (var i = 0; i < elements.length; i++) {
highlightLastLine(elements[i]);
}
}
// Peforms highlighting for single element
function highlightLastLine(element) {
var text = element.innerText.trim();
// get words list
var words = text.split(" ");
// removing all elements
while (element.firstChild) {
element.removeChild(element.firstChild);
}
var spanArray = [];
// add spans with words and whitespaces
for (var i = 0; i < words.length; i++) {
// append span with word */
var span = document.createElement("span");
span.appendChild(document.createTextNode(words[i]));
element.appendChild(span);
// save span element to array
spanArray.push(span);
span = document.createElement("span");
// append whitespace
span.appendChild(document.createTextNode(" "));
element.appendChild(span);
// save span element to array
spanArray.push(span);
}
// sorting by highest top and lowest left
spanArray.sort(function(a, b) {
var rectA = a.getBoundingClientRect();
var rectB = b.getBoundingClientRect();
var deltaTop = rectB.top - rectA.top;
// if differense is less then 1px
if (Math.abs(deltaTop) < 1) {
return rectA.left - rectB.left;
}
return deltaTop;
});
// appending highlighting to siblings of first word of last line
var lastLineSpans = getNextSiblings(spanArray[0]);
// also include the same element
lastLineSpans.unshift(spanArray[0]);
for (var i = 0; i < lastLineSpans.length; i++) {
var lastLineSpan = lastLineSpans[i];
lastLineSpan.classList.add("underline");
}
}
a {
text-decoration: none;
/* just styles for demo */
display: block;
text-align: center;
margin-bottom: 10px;
}
.underline {
border-bottom: 1px solid currentColor;
}
Lorem ipsum
<a href="#">
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Duis venenatis purus non elit imperdiet, non dictum turpis pharetra. Duis a posuere neque, quis pellentesque urna. In id massa mollis, consectetur velit id, fermentum ipsum. Maecenas vehicula leo sit amet massa volutpat consectetur. Cras eu varius justo. Donec ultrices eu est et mattis. Praesent mollis varius ultrices. Pellentesque tempus mauris diam, id scelerisque sem sollicitudin eu. Cras lacinia volutpat sapien ut pellentesque. Pellentesque sollicitudin eleifend sodales. Nulla ornare ex tellus, eget fermentum diam facilisis in.
</a>
<a href="#">
Phasellus nec malesuada tortor. Aliquam erat volutpat. Duis commodo quam at lectus feugiat lacinia. Proin cursus vulputate hendrerit. Duis sit amet fringilla dui. Sed euismod viverra tellus id viverra. Morbi ultrices nulla sed libero porttitor, nec sollicitudin risus blandit. Nulla maximus purus id imperdiet tincidunt. Donec arcu velit, condimentum in euismod vitae, porta eget nibh. Sed auctor metus nulla, in pulvinar neque sodales in. Ut sodales eget diam non vehicula. Praesent ut convallis erat, et ultricies elit. Suspendisse vitae efficitur turpis, at accumsan nulla. Nullam vehicula, lorem quis fermentum tincidunt, enim mi tincidunt odio, nec rutrum est diam sed ipsum.
</a>
<a href="#">
Vivamus eleifend tincidunt urna. Mauris tellus turpis, malesuada nec venenatis nec, mollis et lorem. Nunc pharetra sapien quis justo lobortis molestie. Mauris facilisis ultricies mi, ut auctor lorem porta ac. Integer placerat gravida mi, a elementum nibh congue convallis. Phasellus posuere, mauris sit amet tempus venenatis, metus mi dignissim arcu, nec elementum enim libero ut leo. Aliquam nec est sapien. Mauris in suscipit risus, in lacinia nunc. Morbi at augue ligula. Duis eros quam, tincidunt et sollicitudin a, porta nec dolor. Sed consequat urna non purus ultricies, eget ullamcorper ante convallis.
</a>
<a href="#">
Vestibulum sit amet ante nec lectus dictum sodales ut sed nulla. Phasellus quis orci semper, fringilla neque ac, suscipit ex. Maecenas in sem nec odio sollicitudin imperdiet vitae in felis. Integer euismod eget justo sit amet finibus. Donec venenatis odio quis felis hendrerit posuere vel nec nisi. Ut facilisis commodo massa ac maximus. Suspendisse semper mattis aliquet. Phasellus tempus augue ligula, a pretium eros blandit a. Nullam sed nisi id nisi pharetra facilisis. Curabitur eu nisl mauris. Curabitur iaculis congue augue, vel convallis purus mollis et. Aliquam erat volutpat. Nam tempor arcu vel molestie eleifend.
</a>
<a href="#">
Quisque tincidunt non ex consectetur dapibus. Interdum et malesuada fames ac ante ipsum primis in faucibus. Vestibulum ultricies a nibh finibus vehicula. Suspendisse eu magna sed tortor sollicitudin porttitor. Quisque non turpis at diam eleifend elementum nec ac odio. Duis posuere dignissim risus, non semper arcu lacinia et. Cras mauris nulla, aliquam a maximus a, pellentesque eu est. Suspendisse sit amet laoreet risus. Nulla vestibulum vehicula metus, finibus porttitor ipsum fermentum eu.
</a>
<a href="#">
In at volutpat nibh. Vestibulum sit amet aliquet nisl. In iaculis lectus ac ligula molestie vestibulum. Quisque bibendum tempor luctus. Mauris fermentum blandit magna a malesuada. Donec sagittis odio tortor, non scelerisque odio scelerisque non. Donec tristique mi id lacus finibus vestibulum. Suspendisse convallis nunc facilisis, tempor lorem vitae, ultricies dolor. Nullam magna mauris, maximus vitae arcu ac, feugiat sodales nunc. Praesent ullamcorper, arcu sed elementum varius, mi lorem dapibus mauris, id ullamcorper odio ligula eu lacus. Nullam in porttitor sem. Donec vitae velit a leo mollis facilisis non in odio. Nam in auctor sapien, imperdiet mattis leo. Etiam at odio orci. Nunc at blandit eros. Cras semper non nulla et interdum.
</a>
You can also see how it works with window resizing via jsFiddle.
a{position:relative; display:inline;text-align:center;}
a:after{position:absolute; left:0; bottom:0; width:100%; height:1px; border-bottom:1px solid #000; content:""}
Put text-align : center on a (link) tag.
Try this on anchor tag
text-align:center

How to disable scrolling programmatically while allowing child scrolling?

Using jQuery/Javascript, I am disabling scrolling within the body if a certain element exists.
Although, this also disables scrolling within all other elements on the page.
$("body").on('scroll touchmove mousewheel', function(e) {
if($("#myElem").length > 0) {
e.preventDefault();
e.stopPropagation();
return false;
}
});
The reason for me doing it without CSS is because the md-backdrop element is controlled by a third-party plugin that I am unable to modify.
How can I only disable scrolling within the body, yet allow scrolling within all my child elements that allow an overflow of scroll or auto?
With the following example, you can see that both the body and red area is scrollable. Once the button is clicked and the myElem element is prepended to the page, both the body and red area has disabled scrolling. I require the body to be disabled, although the red area to still be enabled in this case.
WORKING EXAMPLE
Easiest way is to set the scrollTop() of parent to zero whenever a scroll event on it is detected.
See the working example below.
$(function () {
//fill up show data
var str = "";
for(var i = 0; i < 50; i++) {
str += i + "\n";
}
$(".grandchild pre").text(str);
console.log("started");
//fixed scrolling on parent
$(".parent").on("scroll touchmove mousewheel", function(e) {
console.log('moved ' + $(this).attr('class'));
$(this).scrollTop(0);
}).click(function () {
alert('clicked');
});
});
.parent, .child, .grandchild {
padding : 5px;
overflow: auto;
}
.parent {
border: 1px solid red;
height: 200px;
}
.child {
border: 1px solid green;
height: 400px;
}
.grandchild {
border: 1px solid blue;
height: 800px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class='parent'>
parent
<div class='child'>
child
<div class='grandchild'>
grandchild
<pre></pre>
</div>
</div>
</div>
Read e.target to get the target element for specified-events and apply conditions accordingly.
$("body").on('scroll touchmove mousewheel', function(e) {
if ($("#myElem").length > 0 && (e.target.id !== 'myScroller')) {
e.preventDefault();
e.stopPropagation();
return false;
}
});
$("#myBtn").on("click", function() {
if ($("#myElem").length > 0) {
$("#myElem").remove();
} else if ($("#myElem").length === 0) {
$("body").prepend("<div id='myElem'>This element disables all scrolling since it exists</div>");
}
});
body {
height: 1000px;
background-color: green;
}
#myElem {
background-color: black;
color: white;
}
#myScroller {
height: 300px;
overflow-y: scroll;
background-color: red;
color: white;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
Click the below button to toggle the element that is appended to the body. While scrolling, it will check if that element exists. If it exists, scrolling on the body and within the read area is disabled. Need the body disabled, although red area enabled.
<br />
<br />
<button id="myBtn">
Toggle element
</button>
<div id="myScroller">
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nullam ut viverra diam. Aenean semper mauris vitae libero tempor, tempus mattis turpis imperdiet. Donec a tellus ut elit commodo convallis. Suspendisse eu egestas magna. Sed turpis dolor, lacinia
quis orci sit amet, efficitur pulvinar dui. Sed quis metus turpis. Praesent non venenatis sem. Vestibulum tristique sagittis dignissim. In aliquam est vel nunc luctus, vel cursus dolor eleifend. Pellentesque facilisis tempor dui sed viverra. Mauris
sed viverra libero. Suspendisse nisl mauris, cursus id purus non, iaculis lobortis neque. Duis sed tempor mauris, in dictum lorem. Nunc orci elit, rutrum eu est porttitor, pretium iaculis odio. Aenean eu velit posuere, maximus risus at, egestas mauris.
Nullam at diam diam. Suspendisse vel dui dignissim, laoreet nibh ut, iaculis elit. Quisque eu convallis dui. Quisque cursus, urna vitae mattis consequat, urna orci consectetur urna, commodo malesuada lacus urna eu nunc. Nunc in nunc at leo molestie
aliquam. Nunc interdum sollicitudin rutrum. Nam molestie pulvinar ullamcorper. Sed blandit vestibulum porta. Curabitur semper eu ipsum eu commodo. Nunc faucibus ac orci quis ornare. Morbi ornare leo in mi sodales, eget iaculis enim viverra. Nunc at
ligula tortor. Aenean condimentum a tellus quis congue. Nulla eu hendrerit erat. Donec egestas arcu lacinia mattis mollis. Mauris quis maximus eros. Donec ut risus ultricies, sollicitudin lacus sit amet, aliquet nisi. Aenean pellentesque velit justo,
a eleifend quam consectetur blandit. Praesent quis magna sit amet nibh luctus congue sed lobortis sem. Sed ut aliquet diam. Vestibulum pharetra ex ac lectus iaculis, eu aliquet erat placerat. Donec rutrum lobortis tellus, eu efficitur nibh vulputate
eu. Curabitur placerat id quam vel egestas. Proin consectetur sollicitudin lorem. Integer sollicitudin at quam vel sagittis. Integer sed pretium quam, vitae convallis leo. Suspendisse lorem nulla, imperdiet nec cursus id, auctor quis ante. Integer mollis
vel neque sed commodo. Quisque venenatis nulla quis aliquet porta. Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Sed lobortis euismod est sed sagittis. Ut aliquet a tortor id rhoncus. Sed commodo risus
cursus, dignissim nulla vel, molestie ipsum. Cras ac ante luctus diam rutrum placerat eu et risus. Pellentesque sed mauris fringilla nulla imperdiet facilisis a eu leo. Vivamus sollicitudin nibh ac augue ultrices, ut bibendum metus viverra. Donec lectus
urna, lacinia eu bibendum sed, convallis sed ex. Mauris commodo neque sed sollicitudin pharetra. Aenean ac risus ligula. Nunc congue ultrices volutpat. Aenean ac enim porttitor, hendrerit mauris at, ultrices quam. Mauris euismod commodo purus, egestas
semper metus aliquet ac. Quisque nec consectetur sapien. In vestibulum, urna sed lobortis sagittis, sapien ex interdum nisl, id varius orci dolor sit amet dolor. Nunc quis lobortis velit. Praesent viverra eros at nulla pulvinar accumsan. Nulla interdum
urna odio, vel ultricies ante fermentum tincidunt. Sed in nibh quam. Phasellus maximus metus diam, ac vulputate enim fermentum ac. Vestibulum bibendum elit justo, at semper risus consequat ut. Pellentesque facilisis mi et vulputate feugiat. Suspendisse
egestas mauris at elit ullamcorper, non aliquet elit fermentum.
</div>
Edit: Dealing with overflow property of body element will also help!
$("#myBtn").on("click", function() {
$('body').toggleClass('hideIt');
});
body {
height: 1000px;
background-color: green;
}
#myElem {
background-color: black;
color: white;
}
#myScroller {
height: 300px;
overflow-y: scroll;
background-color: red;
color: white;
}
body.hideIt {
overflow: hidden;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
Click the below button to toggle the element that is appended to the body. While scrolling, it will check if that element exists. If it exists, scrolling on the body and within the read area is disabled. Need the body disabled, although red area enabled.
<br />
<br />
<button id="myBtn">
Toggle element
</button>
<div id="myScroller">
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nullam ut viverra diam. Aenean semper mauris vitae libero tempor, tempus mattis turpis imperdiet. Donec a tellus ut elit commodo convallis. Suspendisse eu egestas magna. Sed turpis dolor, lacinia
quis orci sit amet, efficitur pulvinar dui. Sed quis metus turpis. Praesent non venenatis sem. Vestibulum tristique sagittis dignissim. In aliquam est vel nunc luctus, vel cursus dolor eleifend. Pellentesque facilisis tempor dui sed viverra. Mauris
sed viverra libero. Suspendisse nisl mauris, cursus id purus non, iaculis lobortis neque. Duis sed tempor mauris, in dictum lorem. Nunc orci elit, rutrum eu est porttitor, pretium iaculis odio. Aenean eu velit posuere, maximus risus at, egestas mauris.
Nullam at diam diam. Suspendisse vel dui dignissim, laoreet nibh ut, iaculis elit. Quisque eu convallis dui. Quisque cursus, urna vitae mattis consequat, urna orci consectetur urna, commodo malesuada lacus urna eu nunc. Nunc in nunc at leo molestie
aliquam. Nunc interdum sollicitudin rutrum. Nam molestie pulvinar ullamcorper. Sed blandit vestibulum porta. Curabitur semper eu ipsum eu commodo. Nunc faucibus ac orci quis ornare. Morbi ornare leo in mi sodales, eget iaculis enim viverra. Nunc at
ligula tortor. Aenean condimentum a tellus quis congue. Nulla eu hendrerit erat. Donec egestas arcu lacinia mattis mollis. Mauris quis maximus eros. Donec ut risus ultricies, sollicitudin lacus sit amet, aliquet nisi. Aenean pellentesque velit justo,
a eleifend quam consectetur blandit. Praesent quis magna sit amet nibh luctus congue sed lobortis sem. Sed ut aliquet diam. Vestibulum pharetra ex ac lectus iaculis, eu aliquet erat placerat. Donec rutrum lobortis tellus, eu efficitur nibh vulputate
eu. Curabitur placerat id quam vel egestas. Proin consectetur sollicitudin lorem. Integer sollicitudin at quam vel sagittis. Integer sed pretium quam, vitae convallis leo. Suspendisse lorem nulla, imperdiet nec cursus id, auctor quis ante. Integer mollis
vel neque sed commodo. Quisque venenatis nulla quis aliquet porta. Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Sed lobortis euismod est sed sagittis. Ut aliquet a tortor id rhoncus. Sed commodo risus
cursus, dignissim nulla vel, molestie ipsum. Cras ac ante luctus diam rutrum placerat eu et risus. Pellentesque sed mauris fringilla nulla imperdiet facilisis a eu leo. Vivamus sollicitudin nibh ac augue ultrices, ut bibendum metus viverra. Donec lectus
urna, lacinia eu bibendum sed, convallis sed ex. Mauris commodo neque sed sollicitudin pharetra. Aenean ac risus ligula. Nunc congue ultrices volutpat. Aenean ac enim porttitor, hendrerit mauris at, ultrices quam. Mauris euismod commodo purus, egestas
semper metus aliquet ac. Quisque nec consectetur sapien. In vestibulum, urna sed lobortis sagittis, sapien ex interdum nisl, id varius orci dolor sit amet dolor. Nunc quis lobortis velit. Praesent viverra eros at nulla pulvinar accumsan. Nulla interdum
urna odio, vel ultricies ante fermentum tincidunt. Sed in nibh quam. Phasellus maximus metus diam, ac vulputate enim fermentum ac. Vestibulum bibendum elit justo, at semper risus consequat ut. Pellentesque facilisis mi et vulputate feugiat. Suspendisse
egestas mauris at elit ullamcorper, non aliquet elit fermentum.
</div>

hide scrolling div content under transparent header - javascript solution needed

This has been asked several times before and the answer that matches my situation best is this one
Hide content underneath a transparent div while scrolling
basically, the content div is being moved through javascript.
However, I have a fixed header that will always be 155px. The header is transparent, and the text of content div should disappear when it reaches the header. I can not for various reasons use a masking solution, there are several layers of transparency and overlaying complicated backgrounds going on in the header. The content text should truly disappear once reached the header and not go "underneath".
Scroll to see what's going on. Currently on scroll the text covers the header unless the scrollbar passes the header.
JS Fiddle - https://jsfiddle.net/b5nyohr5/5/
$(window).load(function(){
var $window = $(window);
var $body = $('body');
var $contentWrapper = $('#content_wrapper');
var $content = $('#content');
var minHeaderHeight =160; // the height of the header plus margin
var lastWindowHeight = $window.height(); // save window height to calculate difference in height on resize
checkScroll(); // make sure scroll and all heights are correct on first load
stickyTop(); // make sure sticky top is used if needed on first load
$window.resize(function() {
checkScroll();
stickyTop();
});
$window.scroll(function() {
stickyTop();
});
function checkScroll() {
var newWindowHeight = $window.height();
var windowHeightDif = newWindowHeight - lastWindowHeight;
lastWindowHeight = newWindowHeight; // save current height for next call
var contentHeight = $content.height();
$contentWrapper.height(contentHeight); // make sure wrapper will show entire content
$body.height(newWindowHeight + contentHeight); // allow content to be scrolled off the screen by
// pushing content down by the amount of window height
var windowScrollTop = $window.scrollTop();
if (windowScrollTop > 0) { // don't scroll if at top to avoid video getting covered
$window.scrollTop(windowScrollTop + windowHeightDif); // scroll by window height difference to keep content
// in the same position on window resize
}
}
function stickyTop() {
var windowScrollTop = $window.scrollTop();
var maxScroll = ($window.height() - minHeaderHeight);
if (windowScrollTop >= maxScroll) {
$contentWrapper.css('position', 'fixed').css('top', minHeaderHeight); // stop wrapper top at bottom of header
} else {
$contentWrapper.css('position', 'absolute').css('top', ''); // allow regular scrolling
}
if ($contentWrapper.css('position') === 'fixed') { // if wrapper is fixed,
$content.css('top', -(windowScrollTop - maxScroll)); // continue scrolling by shifting content up
} else {
$content.css('top', 0); // make sure content is lined up with wrapper
}
}
});//]]>
html, body {
position: relative;
width:100%;
height:100%;
}
#header {
position: fixed;
top: 0;
left: 0;
z-index: -1000;
width:100%;
height: 155px;
background-color:rgba(0, 0, 0, 0.5)
}
#content_wrapper {
position: absolute;
left: 0px;
top:155px;
width: 100%;
z-index: -10;
overflow:hidden;
}
#content {
position: absolute;
left: 0px;
top: 0px;
font-size:36px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<div id="container">
<div id="header">
<h1>This header is semi-transparent . All kind of overlaying opacity will go here. </h1>
</div>
<div id="content_wrapper">
<div id="content">
<p>The scrolling text needs to stop showing once it reaches the transparent header.
<p>Morbi facilisis neque a eros dictum, ut facilisis dolor pretium. Nulla sagittis vel ante sed ornare. Aenean in magna volutpat, consequat elit vitae, convallis purus. Mauris et orci lacinia, vestibulum odio non, bibendum tellus. Donec mollis, justo quis fermentum ultricies, lacus velit luctus odio, quis finibus mauris dolor vitae nulla. Morbi ac sagittis ante, consectetur pretium tellus. Aliquam erat volutpat. Donec facilisis gravida mauris quis ultricies. Duis et suscipit lorem. Pellentesque nec imperdiet nibh. Nullam pretium, nunc nec ultricies cursus, libero dui venenatis purus, a feugiat eros mauris vel libero. Quisque id risus maximus, dignissim sem id, tempus odio. Donec faucibus blandit mauris ac laoreet. Praesent scelerisque lobortis libero eget suscipit. Sed egestas diam hendrerit, fermentum felis in, eleifend lorem.</p>
<p>Donec tempus fringilla ipsum, aliquet suscipit diam ornare venenatis. Vestibulum scelerisque posuere nibh tristique aliquam. Proin ullamcorper ipsum non interdum semper. Vivamus id felis egestas nulla imperdiet convallis in vel dui. Sed vitae turpis non lorem blandit placerat. Curabitur posuere nisl ac felis consectetur, ut ultricies diam faucibus. Nunc laoreet malesuada tellus. Suspendisse efficitur accumsan lacus, ut pretium diam euismod vitae. Vestibulum tincidunt fringilla ligula a interdum.</p>
<p>Quisque luctus purus nec varius finibus. Sed ut lorem scelerisque velit pretium elementum. Maecenas sit amet maximus risus, pretium molestie arcu. Mauris vitae vestibulum lacus. Mauris porttitor aliquet turpis, vel aliquet nisl rutrum quis. Curabitur risus massa, placerat vitae sapien non, egestas efficitur elit. Etiam ut odio non nisl vestibulum venenatis quis ac erat. Curabitur id sem vel eros tristique dignissim ac id neque. Duis elementum, mi ut fringilla pellentesque, ante neque venenatis leo, a pretium nisi massa nec urna. Mauris quam mi, commodo maximus elementum eget, maximus a sapien. Pellentesque nec leo risus.</p>
<p>Etiam non luctus lacus. Aliquam velit nibh, ultrices vitae rhoncus eget, gravida non libero. Aenean lectus purus, ultrices id tincidunt sit amet, feugiat sed turpis. Nam ut turpis cursus ante placerat ultricies. In vitae mauris facilisis lorem maximus accumsan. Curabitur turpis odio, consequat at ante non, mollis porttitor felis. Pellentesque ultricies lacus dapibus diam laoreet venenatis. Phasellus faucibus sollicitudin mi, tempus elementum dui venenatis vitae. In lacinia dui leo, et laoreet eros vehicula nec. Nullam scelerisque ligula non ante luctus porttitor. Donec sed tortor ut felis imperdiet congue eget sit amet dui.</p>
<p>Nullam luctus condimentum augue pharetra facilisis. Mauris laoreet ut odio nec posuere. Maecenas accumsan luctus augue, vitae mollis risus dignissim non. Vivamus nec felis sed sapien porta venenatis. Proin a placerat lacus. Donec ut turpis sed massa mollis aliquet. Vivamus sit amet quam nec urna viverra facilisis. Suspendisse vel erat tellus. In pulvinar justo et quam accumsan tincidunt. Fusce purus est, luctus cursus justo ut, auctor sollicitudin nisl. Integer semper bibendum lorem. Fusce volutpat condimentum lorem vitae vestibulum. Pellentesque eleifend lacus eget sodales egestas. Ut purus urna, maximus quis felis nec, luctus gravida nibh.</p>
<p>Maecenas in lacinia nibh. Morbi non nibh a lorem egestas commodo. Vivamus arcu libero, congue sit amet velit ut, faucibus commodo sem. Mauris at tellus nec est molestie consectetur cursus quis nisi. Etiam vel consequat felis. Curabitur sed dui ac dolor sollicitudin laoreet non nec nunc. Sed bibendum eu est vel posuere. Fusce varius volutpat leo at porta. Curabitur maximus nunc ipsum. Aenean placerat dolor in enim feugiat volutpat. Ut pharetra nulla at lorem rutrum posuere. Integer eu justo nec quam vestibulum aliquet. Praesent aliquam fermentum est vel varius.</p>
<p>Pellentesque imperdiet pharetra molestie. Sed velit tortor, tincidunt et lacus quis, facilisis dapibus ex. Cras et rutrum leo, et sodales augue. In hac habitasse platea dictumst. Nunc acc</p>
</div>
</div>
</div>
Is there any reason your fixed header needs to be in the same container as the rest of the content?
<div class="fixedHeader" style="position: fixed; display: block; width: 100%;">
</div>
<div class="contentContainer" style="position: relative; display: block;">
</div>
I think this will have the same "scrolling under the header" effect?
I have found a solution by modifying Trevin Avery code slightly - removing variable maxScroll from Javascript code completely, as I don't need to push the scrollable content all the way out of the visible window, like his script does.
See demo - resize the browser window to see why transparency was needed.
$(window).load(function(){
var $window = $(window);
var $body = $('body');
var $contentWrapper = $('#content_wrapper');
var $content = $('#content');
var minHeaderHeight =160; // the height of the header plus margin
var lastWindowHeight = $window.height(); // save window height to calculate difference in height on resize
checkScroll(); // make sure scroll and all heights are correct on first load
stickyTop(); // make sure sticky top is used if needed on first load
$window.resize(function() {
checkScroll();
stickyTop();
});
$window.scroll(function() {
stickyTop();
});
function checkScroll() {
var newWindowHeight = $window.height();
var windowHeightDif = newWindowHeight - lastWindowHeight;
lastWindowHeight = newWindowHeight; // save current height for next call
var contentHeight = $content.height();
$contentWrapper.height(contentHeight); // make sure wrapper will show entire content
$body.height(newWindowHeight + contentHeight); // allow content to be scrolled off the screen by
// pushing content down by the amount of window height
var windowScrollTop = $window.scrollTop();
if (windowScrollTop > 0) { // don't scroll if at top to avoid video getting covered
$window.scrollTop(windowScrollTop + windowHeightDif ); // scroll by window height difference to keep content
// in the same position on window resize
}
}
function stickyTop() {
var windowScrollTop = $window.scrollTop();
// check where the scrollbar is
if (windowScrollTop >= 0) {
// stop wrapper top at bottom of header
$contentWrapper.css('position', 'fixed').css('top', minHeaderHeight);
} else {
// allow regular scrolling
$contentWrapper.css('position', 'absolute').css('top', '');
}
if ($contentWrapper.css('position') === 'fixed') { // if wrapper is fixed,
$content.css('top', - windowScrollTop); // continue scrolling by shifting content up
} else {
$content.css('top', 0); // make sure content is lined up with wrapper
}
}
});//]]>
html, body {
position: relative;
width:100%;
height:100%;
}
body {
background:url(http://www.idea-bureau.com/images/background.png);
background-repeat: no-repeat;
background-position:center, center;
background-attachment: fixed;
}
#header {
position: fixed;
top: 0;
left: 0;
z-index: -1000;
width:100%;
height: 155px;
background-color:rgba(0, 0, 0, 0.5);
}
#content_wrapper {
position: absolute;
left: 0px;
top:155px;
width: 100%;
z-index: -10;
overflow:hidden;
}
#content {
position: absolute;
left: 0px;
top: 0px;
font-size:25px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<div id="container">
<div id="header">
<h1>This header is semi-transparent . All kind of overlaying opacity will go here. </h1>
</div>
<div id="content_wrapper">
<div id="content">
<p>The scrolling text needs to stop showing once it reaches the transparent header.
<p>Morbi facilisis neque a eros dictum, ut facilisis dolor pretium. Nulla sagittis vel ante sed ornare. Aenean in magna volutpat, consequat elit vitae, convallis purus. Mauris et orci lacinia, vestibulum odio non, bibendum tellus. Donec mollis, justo quis fermentum ultricies, lacus velit luctus odio, quis finibus mauris dolor vitae nulla. Morbi ac sagittis ante, consectetur pretium tellus. Aliquam erat volutpat. Donec facilisis gravida mauris quis ultricies. Duis et suscipit lorem. Pellentesque nec imperdiet nibh. Nullam pretium, nunc nec ultricies cursus, libero dui venenatis purus, a feugiat eros mauris vel libero. Quisque id risus maximus, dignissim sem id, tempus odio. Donec faucibus blandit mauris ac laoreet. Praesent scelerisque lobortis libero eget suscipit. Sed egestas diam hendrerit, fermentum felis in, eleifend lorem.</p>
<p>Donec tempus fringilla ipsum, aliquet suscipit diam ornare venenatis. Vestibulum scelerisque posuere nibh tristique aliquam. Proin ullamcorper ipsum non interdum semper. Vivamus id felis egestas nulla imperdiet convallis in vel dui. Sed vitae turpis non lorem blandit placerat. Curabitur posuere nisl ac felis consectetur, ut ultricies diam faucibus. Nunc laoreet malesuada tellus. Suspendisse efficitur accumsan lacus, ut pretium diam euismod vitae. Vestibulum tincidunt fringilla ligula a interdum.</p>
<p>Quisque luctus purus nec varius finibus. Sed ut lorem scelerisque velit pretium elementum. Maecenas sit amet maximus risus, pretium molestie arcu. Mauris vitae vestibulum lacus. Mauris porttitor aliquet turpis, vel aliquet nisl rutrum quis. Curabitur risus massa, placerat vitae sapien non, egestas efficitur elit. Etiam ut odio non nisl vestibulum venenatis quis ac erat. Curabitur id sem vel eros tristique dignissim ac id neque. Duis elementum, mi ut fringilla pellentesque, ante neque venenatis leo, a pretium nisi massa nec urna. Mauris quam mi, commodo maximus elementum eget, maximus a sapien. Pellentesque nec leo risus.</p>
<p>Etiam non luctus lacus. Aliquam velit nibh, ultrices vitae rhoncus eget, gravida non libero. Aenean lectus purus, ultrices id tincidunt sit amet, feugiat sed turpis. Nam ut turpis cursus ante placerat ultricies. In vitae mauris facilisis lorem maximus accumsan. Curabitur turpis odio, consequat at ante non, mollis porttitor felis. Pellentesque ultricies lacus dapibus diam laoreet venenatis. Phasellus faucibus sollicitudin mi, tempus elementum dui venenatis vitae. In lacinia dui leo, et laoreet eros vehicula nec. Nullam scelerisque ligula non ante luctus porttitor. Donec sed tortor ut felis imperdiet congue eget sit amet dui.</p>
<p>Nullam luctus condimentum augue pharetra facilisis. Mauris laoreet ut odio nec posuere. Maecenas accumsan luctus augue, vitae mollis risus dignissim non. Vivamus nec felis sed sapien porta venenatis. Proin a placerat lacus. Donec ut turpis sed massa mollis aliquet. Vivamus sit amet quam nec urna viverra facilisis. Suspendisse vel erat tellus. In pulvinar justo et quam accumsan tincidunt. Fusce purus est, luctus cursus justo ut, auctor sollicitudin nisl. Integer semper bibendum lorem. Fusce volutpat condimentum lorem vitae vestibulum. Pellentesque eleifend lacus eget sodales egestas. Ut purus urna, maximus quis felis nec, luctus gravida nibh.</p>
<p>Maecenas in lacinia nibh. Morbi non nibh a lorem egestas commodo. Vivamus arcu libero, congue sit amet velit ut, faucibus commodo sem. Mauris at tellus nec est molestie consectetur cursus quis nisi. Etiam vel consequat felis. Curabitur sed dui ac dolor sollicitudin laoreet non nec nunc. Sed bibendum eu est vel posuere. Fusce varius volutpat leo at porta. Curabitur maximus nunc ipsum. Aenean placerat dolor in enim feugiat volutpat. Ut pharetra nulla at lorem rutrum posuere. Integer eu justo nec quam vestibulum aliquet. Praesent aliquam fermentum est vel varius.</p>
<p>Pellentesque imperdiet pharetra molestie. Sed velit tortor, tincidunt et lacus quis, facilisis dapibus ex. Cras et rutrum leo, et sodales augue. In hac habitasse platea dictumst. Nunc acc</p>
</div>
</div>
</div>
So, here we go, transparent fixed header. Run the code in full window and resize the window to see the background of the page changing depending on window width - that's why I couldn't use masking. Spent almost three days looking for it, so hope it helps somebody!

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/

How does Google make its scrollbars?

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.

Categories