When the user selects the link for the modal, the body overflow is hidden, but the scrolling for the modal is hidden as well even when I have the modal as being overflow: auto. I would like for the modal to be able to scroll without what is behind the overlay to scroll as well.
HTML
<a>View Proposal Details</a>
<div class='popup'>
<div class="popup-body">
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nulla lobortis quis mauris tristique rutrum. Suspendisse nisi turpis, pharetra porta porta eu, interdum ac eros. Praesent nisl nunc, laoreet ut consectetur sed, interdum ac ligula. Aliquam sit amet efficitur velit. Donec malesuada nec est ac feugiat. Nam gravida ornare volutpat. Vivamus ipsum mi, laoreet sed mattis id, rutrum sit amet massa. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus.
Nullam congue auctor ligula at venenatis. Integer varius tortor quis lacus luctus, vel dignissim leo tincidunt. Aliquam eleifend cursus vulputate. Sed vitae dolor at elit porta tristique. In quam arcu, posuere ac lorem nec, finibus imperdiet nibh. Etiam eu tincidunt metus, nec tristique eros. Nullam tempor lorem sed sapien scelerisque, nec rutrum risus tempor. Sed blandit ipsum accumsan ipsum porta consectetur. Curabitur imperdiet justo non purus euismod blandit. Ut cursus dolor mauris, vitae sagittis nisl sagittis at. Sed in feugiat nisi. Pellentesque egestas mi a mi dictum, vel posuere risus malesuada. Etiam tincidunt volutpat neque, vel lobortis orci tristique in. In hac habitasse platea dictumst. Nullam sed rutrum orci.
Proin pellentesque arcu ut justo ullamcorper dignissim. Sed eget enim sed nibh convallis maximus ac ac odio. In tortor risus, luctus sit amet enim non, luctus faucibus leo. Nulla nec mauris vitae mauris tincidunt mollis nec sit amet velit. Proin gravida neque eu eros blandit vulputate. Fusce tristique interdum scelerisque.
Donec vel laoreet nunc, in tristique risus. Phasellus ultrices orci mi, eget imperdiet libero ultrices quis. Phasellus iaculis, ante et dictum mollis, est ipsum feugiat turpis, condimentum sagittis ligula diam a erat. Donec porta, magna sit amet pellentesque pharetra, erat turpis semper lorem, ac varius metus arcu et felis. Vestibulum facilisis ac lorem ut blandit.
</div>
</div>
CSS
.popup { position:fixed;z-index:8;left:31%;width:625px;padding:0;top:70px;background:#fff;overflow:auto;display:none;box-shadow:5px 5px 10px 0 rgba(0,0,0,0.25)}
JQuery
function opendialog(container) {
$(container).fadeIn(); //open
if( $(container).height() < $(window).height() ) { //centralize vertically
$(container).css({
'top':'50%',
'margin-top':'-'+$(container).height()/2+'px'
});
} else {
$(container).css('position','absolute');
}
$('.overlay').fadeIn();
}
$('.cancel').click(function(){ //close clicking on overlay, close button and cancel button
$('body').css('overflow', 'auto');
closedialog();
})
$('a').click(function(){
$('body').css('overflow', 'hidden');
opendialog('.popup');
})
If you want the body to scroll, just remove the line
$('body').css('overflow', 'hidden');
If you want the modal itself to move down the screen, you'll want to add an outer div that takes up the entire page and apply overflow: scroll to that.
<div id="popup-outer">
<div id="popup">[...]</div>
</div>
One good way to do this is to set fixed values for top, bottom, left, and right, removing the value for width. Then you can be assured your modal is always centered and optimally sized for the screen, and, of course, you won't shove your scrollbar off-screen right.
.popup {
display: none;
position: fixed;
z-index: 8;
top: 70px;
bottom: 20px;
left: 20px;
right: 20px;
padding: 0;
background: #fff;
overflow: auto;
box-shadow: 5px 5px 10px 0 rgba(0, 0, 0, 0.25)
}
You can also keep the width fixed and set margin-left and margin-right to auto provided that all container elements have some sort of width set, so that that the browser can actually calculate the margins.
Simple fiddle here.
Related
The issue:
I want the visitors to always see my site in portrait mode
I have gone through many links and have a working solution when mobile is turned to the landscape mode with -90 degrees
The issue I am facing is when mobile is turned +90 degrees. I cannot scroll the content at all when it's rotated +90 degrees. How do I make it so that the content is still scrollable even when it's rotated +90 degrees?
To see the issue:
Run the code snippet below (in full page) on any mobile turned to landscape mode (or on Developer Tools with mobile mode on while on landscape orientation)
You will see the issue I get with rotating by +90 degrees
To see the working version (-90 degrees), change the rotator-right class to rotator in my JS code below
The code I have:
(function() {
function myFunction() {
var wSH = window.screen.height;
var wI = window.innerHeight;
var dBC = document.body.clientHeight;
var wO = window.orientation;
document.getElementById("wSH").textContent = wSH;
document.getElementById("wI").textContent = wI;
document.getElementById("wO").textContent = wO;
document.getElementById("dBC").textContent = dBC;
var bodyDocument = document.body;
var iosDevice = /iPad|iPhone|iPod/.test(navigator.userAgent) &&
!window.MSStream;
if (window.matchMedia('(orientation: landscape)').matches &&
(
(window.screen.height < 425) /* for android */ ||
(iosDevice && window.innerHeight < 425) /* for iOS */
)
) {
bodyDocument.classList.add('rotator-right');
} else {
bodyDocument.classList.remove('rotator-right');
}
document.getElementsByTagName('body')[0].style.display = 'none';
setTimeout(function() {
document.getElementsByTagName('body')[0].style.display = 'block';
}, 200);
setTimeout(function() {
//console.log('inside rotator-right, with document.body.scrollHeight :', document.body.scrollHeight);
}, 100);
}
window.addEventListener("resize", myFunction);
myFunction();
})();
#media screen and (orientation:landscape) {
.rotator {
transform: scale(0.95) rotate(270deg);
transform-origin: top right;
position: relative;
top: 0px;
left: -100vh;
height: 100vw;
width: 100vh;
overflow-y: hidden;
}
.rotator-right {
transform: scale(0.93) rotate(90deg);
transform-origin: top right;
position: relative;
width: 100vh;
top: 50vw;
left: 42vw;
overflow-y: hidden;
}
}
<body id='body'>
<div class='container'>
<p>Click the button to display this frame's height and width.</p>
<p id="demo"></p>
<p>window.scroll.height :
<span id="wSH"></span>
</p>
<p>window.innerHeight :
<span id="wI"></span>
</p>
<p>document.body.clientHeight :
<span id="dBC"></span>
</p>
<p>window.orientation :
<span id="wO"></span>
</p>
<button>Try it</button>
<br />
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nulla ac magna nec nisi accumsan blandit. Quisque feugiat commodo sapien quis pharetra. Sed elit justo, volutpat ac eleifend eu, aliquet in orci. Proin fermentum purus nec ante molestie sodales.
Cras malesuada nunc purus, id iaculis magna suscipit nec. Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Aliquam pulvinar eu lectus eu sollicitudin. Integer mauris sem, posuere vel est a, eleifend pulvinar
lectus. Duis sapien velit, tristique imperdiet purus nec, scelerisque porta massa. Proin commodo faucibus purus, in volutpat lectus maximus sed. Suspendisse potenti.
</p>
<p>
Curabitur maximus elementum nibh, at rhoncus dolor auctor in. Donec ultrices enim ac est sollicitudin euismod. Mauris tempor eget dolor sit amet consequat. Suspendisse volutpat efficitur eros, vitae imperdiet tellus. Vestibulum aliquam nunc eget ante
porta gravida. Aliquam cursus fermentum accumsan. Interdum et malesuada fames ac ante ipsum primis in faucibus. Curabitur condimentum tempus mollis. Suspendisse luctus posuere sapien, ut pharetra lacus eleifend ut.
</p>
<p>
Morbi eu finibus quam. Morbi pharetra mollis diam id hendrerit. Etiam rhoncus, dolor quis hendrerit consectetur, est urna efficitur erat, in vestibulum nunc erat eget sapien. Curabitur ut massa semper, feugiat quam eu, rhoncus tortor. Ut quis convallis
diam, et euismod sem. Cras volutpat libero id nulla varius, at egestas elit consectetur. Nulla posuere neque risus, eu mollis dolor vehicula ut. Donec a ipsum eu justo malesuada lacinia in porta nibh. Aenean risus erat, molestie elementum eros vitae,
tempor porta lacus. Fusce et bibendum est. Orci varius natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Maecenas vel est ac justo vehicula commodo eget eget magna. Etiam vitae aliquet eros, rutrum porta ligula. Nulla at
fringilla lacus, sed commodo justo. Aenean imperdiet maximus tortor sed volutpat. Lorem ipsum dolor sit amet, consectetur adipiscing elit.
</p>
<p>
Curabitur finibus dictum condimentum. Nulla scelerisque dui elit, sit amet lobortis tellus mollis ut. Orci varius natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Pellentesque ac ex sapien. Maecenas ac pellentesque nisi, id mattis
ligula. Sed lacinia feugiat ultricies. Sed ultrices facilisis efficitur. Vestibulum quis libero nec quam convallis mattis. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nam lacus neque, sodales sit amet facilisis eu, viverra vel nulla.
Nullam nec dapibus metus. Aenean pulvinar molestie dolor. In hac habitasse platea dictumst.
</p>
<p>
Nunc commodo magna id nisl ultricies porta. Nulla eget purus et mi malesuada hendrerit. Aenean euismod mauris placerat est dapibus, venenatis posuere lacus fermentum. Cras purus lorem, tristique non semper sit amet, pulvinar a ligula. Vestibulum ante
ipsum primis in faucibus orci luctus et ultrices posuere cubilia Curae; Suspendisse ultricies ultrices posuere. Nulla eu pellentesque ante. Curabitur consequat odio eget purus vestibulum, nec vestibulum lacus mollis. Etiam cursus, ipsum vehicula
auctor rhoncus, diam massa fermentum nibh, ac tincidunt neque arcu et risus.</p>
<hr />
<p>--------- This is the last line ---------</p>
</div>
</body>
What went wrong?
I figured out what was wrong. When you're rotating to the left by 90 degrees (-90 degrees) with a transform-origin: top right, the box extends the containing html to the right, thus causing it to be scrollable to the right.
However, when you're rotating to the right by 90 degrees (+90 degrees) with a transform-origin: top left, the box extends the containing html to the left and this does not cause it to be scrollable to the left. There has been a discussion about this particular scenario here at SO. Do try reading it.
Workaround
Knowing that, we can instead manipulate the transform-origin to bottom left so that the box rotates in such a way that it extends the containing html to the right and causes the scrollbar to appear. However, doing this, we need to adjust it so that the position is correct. To do that, we can use another transform function, which is translate. I changed your .rotator and .rotator-right classes to utilize translateX and translateY before rotating so that the position after rotation is correct.
(I recommend playing with transform function. Try making one item that applies rotate before translate and one item that applies translate before rotate. The results are different! You'll learn something new.)
I advise trying to adjust transform and overflow-y values to see what I mean by the box extending the containing html to the right and left on both .rotator and .rotator-right class.
Here's a working solution. I added configured your CSS part on .rotator-right and .rotator. You're not using left or top anymore to adjust the position, you're giving that control to transform function wholly. Try running it on full-screen and enable mobile mode on your browser.
function myFunction() {
var wSH = window.screen.height
var wI = window.innerHeight
var dBC = document.body.clientHeight
var wO = window.screen.orientation.type
document.getElementById("wSH").textContent = wSH
document.getElementById("wI").textContent = wI
document.getElementById("wO").textContent = wO
document.getElementById("dBC").textContent = dBC
var bodyDocument = document.body;
var iosDevice = /iPad|iPhone|iPod/.test(navigator.userAgent) &&
!window.MSStream;
if (window.matchMedia('(orientation: landscape)').matches &&
(
(window.screen.height < 425) /* for android */ ||
(iosDevice && window.innerHeight < 425) /* for iOS */
)
) {
bodyDocument.classList.add('rotator-right')
} else {
bodyDocument.classList.remove('rotator-right')
}
document.getElementsByTagName('body')[0].style.display = 'none';
setTimeout(function() {
document.getElementsByTagName('body')[0].style.display = 'block';
if (bodyDocument.classList.contains('rotator-right')) window.scrollTo(bodyDocument.getBoundingClientRect().width, 0)
}, 200);
}
window.addEventListener("resize", myFunction);
myFunction();
* {
box-sizing: border-box;
}
body,
html {
margin: 0;
}
p {
margin: 0;
padding: 16px 0;
}
#media screen and (orientation:landscape) {
.rotator {
transform-origin: top right;
width: 100vh;
/* Try playing with these properties to see the transformation */
/* Use scale at the very end of transform if needed */
transform: translateX(-100%) rotate(-90deg);
transition: all .5s ease;
overflow-y: hidden;
}
.rotator-right {
transform-origin: bottom left;
width: 100vh;
/* Try playing with these properties to see the transformation */
/* Use scale at the very end of transform if needed */
transform: translateY(-100%) rotate(90deg) scale(0.85);
transition: all .5s ease;
overflow-y: hidden;
}
}
<body id='body'>
<div class='container'>
<p>Click the button to display this frame's height and width.</p>
<p id="demo"></p>
<p>window.scroll.height :
<span id="wSH"></span>
</p>
<p>window.innerHeight :
<span id="wI"></span>
</p>
<p>document.body.clientHeight :
<span id="dBC"></span>
</p>
<p>window.orientation :
<span id="wO"></span>
</p>
<button>Try it</button>
<br />
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nulla ac magna nec nisi accumsan blandit. Quisque feugiat commodo sapien quis pharetra. Sed elit justo, volutpat ac eleifend eu, aliquet in orci. Proin fermentum purus nec ante molestie sodales.
Cras malesuada nunc purus, id iaculis magna suscipit nec. Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Aliquam pulvinar eu lectus eu sollicitudin. Integer mauris sem, posuere vel est a, eleifend pulvinar
lectus. Duis sapien velit, tristique imperdiet purus nec, scelerisque porta massa. Proin commodo faucibus purus, in volutpat lectus maximus sed. Suspendisse potenti.
</p>
<p>
Curabitur maximus elementum nibh, at rhoncus dolor auctor in. Donec ultrices enim ac est sollicitudin euismod. Mauris tempor eget dolor sit amet consequat. Suspendisse volutpat efficitur eros, vitae imperdiet tellus. Vestibulum aliquam nunc eget ante
porta gravida. Aliquam cursus fermentum accumsan. Interdum et malesuada fames ac ante ipsum primis in faucibus. Curabitur condimentum tempus mollis. Suspendisse luctus posuere sapien, ut pharetra lacus eleifend ut.
</p>
<p>
Morbi eu finibus quam. Morbi pharetra mollis diam id hendrerit. Etiam rhoncus, dolor quis hendrerit consectetur, est urna efficitur erat, in vestibulum nunc erat eget sapien. Curabitur ut massa semper, feugiat quam eu, rhoncus tortor. Ut quis convallis
diam, et euismod sem. Cras volutpat libero id nulla varius, at egestas elit consectetur. Nulla posuere neque risus, eu mollis dolor vehicula ut. Donec a ipsum eu justo malesuada lacinia in porta nibh. Aenean risus erat, molestie elementum eros vitae,
tempor porta lacus. Fusce et bibendum est. Orci varius natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Maecenas vel est ac justo vehicula commodo eget eget magna. Etiam vitae aliquet eros, rutrum porta ligula. Nulla at
fringilla lacus, sed commodo justo. Aenean imperdiet maximus tortor sed volutpat. Lorem ipsum dolor sit amet, consectetur adipiscing elit.
</p>
<p>
Curabitur finibus dictum condimentum. Nulla scelerisque dui elit, sit amet lobortis tellus mollis ut. Orci varius natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Pellentesque ac ex sapien. Maecenas ac pellentesque nisi, id mattis
ligula. Sed lacinia feugiat ultricies. Sed ultrices facilisis efficitur. Vestibulum quis libero nec quam convallis mattis. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nam lacus neque, sodales sit amet facilisis eu, viverra vel nulla.
Nullam nec dapibus metus. Aenean pulvinar molestie dolor. In hac habitasse platea dictumst.
</p>
<p>
Nunc commodo magna id nisl ultricies porta. Nulla eget purus et mi malesuada hendrerit. Aenean euismod mauris placerat est dapibus, venenatis posuere lacus fermentum. Cras purus lorem, tristique non semper sit amet, pulvinar a ligula. Vestibulum ante
ipsum primis in faucibus orci luctus et ultrices posuere cubilia Curae; Suspendisse ultricies ultrices posuere. Nulla eu pellentesque ante. Curabitur consequat odio eget purus vestibulum, nec vestibulum lacus mollis. Etiam cursus, ipsum vehicula
auctor rhoncus, diam massa fermentum nibh, ac tincidunt neque arcu et risus.</p>
<hr />
<p>--------- This is the last line ---------</p>
</div>
</body>
One unrelated concern of mine: you used this code to detect if a device is iOS: /iPad|iPhone|iPod/.test(navigator.userAgent) && !window.MSStream;. I can't seem to find a proper documentation on that so it may be inaccurate code. Furthermore, from MDN about user agent sniffing:
It's worth re-iterating: it's very rarely a good idea to use user agent sniffing. You can almost always find a better, more broadly compatible way to solve your problem!
Also, it seems like Safari (iOS) also supports window.screen.height.
I'm trying to add a sticky nav bar on my web site which takes into effect after i scroll down to a specific point. well i know how positions work and i did well with sticking it. but problem is it is not sticking when i try to use JS and JQuery for scroll down purpose. I referred to a tut for same thing and happened to see a code on "codepen.io" as well. But when i tried the same exact code on my computer and browser it didn't work either. strange thing is that the same code works on jsfiddle.net and codepen.io but when i try it with my notepad++ it doesn't work at all. I don't know where i'm making mistakes.
here is pastebin for my code >>
Sticky Navigation complete code
here is Jsfiddle link >>
Sticky Navigation with scroll down effect
<!DOCTYPE HTML>
<html>
<head>
<title>
Sticky Navigation Bar
</title>
<script src="jquery.min.js" type="text/javascript"></script>
<script>
var mn = $(".main-nav");
mns = "main-nav-scrolled";
hdr = $('header').height();
$(window).scroll(function() {
if( $(this).scrollTop() > hdr ) {
mn.addClass(mns);
} else {
mn.removeClass(mns);
}
});
</script>
<style>
*{
box-sizing: border-box;
}
body {
margin: 0;
padding-top: 250px;
}
header {
height: 300px;
padding-top: 50px;
background: #f07057;
}
.main-nav,
.main {
position: relative;
}
.main-nav {
background: #fff;
height: 80px;
z-index: 150;
margin-bottom: -80px;
box-shadow: 0 2px 3px rgba(0,0,0,.4);
}
header,
.main-nav-scrolled {
position: fixed;
width: 100%;
top: 0;
}
.main {
background: #f2f2e8;
padding: 110px 50px 50px;
column-count: 2;
column-gap: 40px;
}
</style>
</head>
<body>
<header>
<h1>This is a Sticky Nav Demo!</h1>
<p>Creating one of these isn't so bad. Let's learn how with this sweet little demo!</p>
</header>
<nav class="main-nav">
Nav Link 1
Nav Link 2
Nav Link 3
Nav Link 4
</nav>
<div class="main">
<h2>Lorem ipsum dolor sit amet</h2>
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Aenean fringilla, purus in porttitor pellentesque, erat arcu tincidunt diam, dapibus faucibus leo mauris at sapien. In porttitor vehicula sodales. Vivamus massa neque, facilisis eu felis ut, aliquet convallis nisi. Nam elementum tellus vitae gravida fermentum. Nullam et imperdiet leo. Integer ut euismod lorem, in placerat lacus. Curabitur bibendum arcu ut feugiat commodo. Suspendisse ut mi vel orci ullamcorper tincidunt. Nam vitae fringilla nibh. Nullam hendrerit blandit velit eu hendrerit.</p>
<p>Praesent eu enim non massa pellentesque lobortis. In in sagittis dolor. Aliquam non massa erat. Ut aliquet gravida tellus, sed volutpat nibh condimentum et. Nunc quam purus, vehicula quis venenatis et, porttitor vel dolor. Cras facilisis dui id elit bibendum, in ullamcorper leo ultricies. Praesent rutrum lacus sit amet sem convallis, ut interdum dolor vestibulum.</p>
<p>Tum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. In iaculis pharetra odio, sit amet consectetur elit facilisis ac. Praesent eget tristique ipsum. Donec malesuada bibendum lacinia. Praesent non purus sodales, pulvinar mi vitae, tincidunt leo. Phasellus vitae elit ut nisl semper fringilla id rutrum dolor. Donec a massa adipiscing, cursus risus vitae, porttitor tortor. Nullam sagittis est sapien, sit amet pharetra turpis imperdiet vel. Etiam sit amet ligula pretium, vulputate eros ac, bibendum velit. Aenean convallis ante purus, ac bibendum orci laoreet ac. Donec a convallis mauris. Nulla non lacus non ipsum pretium tempor. In hac habitasse platea dictumst. Aenean at ipsum vulputate, sagittis dui ut, pharetra neque. Nam eget sodales orci. Aliquam pharetra nunc at nisl pellentesque, nec fringilla enim iaculis.</p>
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Aenean fringilla, purus in porttitor pellentesque, erat arcu tincidunt diam, dapibus faucibus leo mauris at sapien. In porttitor vehicula sodales. Vivamus massa neque, facilisis eu felis ut, aliquet convallis nisi. Nam elementum tellus vitae gravida fermentum. Nullam et imperdiet leo. Integer ut euismod lorem, in placerat lacus. Curabitur bibendum arcu ut feugiat commodo. Suspendisse ut mi vel orci ullamcorper tincidunt. Nam vitae fringilla nibh. Nullam hendrerit blandit velit eu hendrerit.</p>
<p>Praesent eu enim non massa pellentesque lobortis. In in sagittis dolor. Aliquam non massa erat. Ut aliquet gravida tellus, sed volutpat nibh condimentum et. Nunc quam purus, vehicula quis venenatis et, porttitor vel dolor. Cras facilisis dui id elit bibendum, in ullamcorper leo ultricies. Praesent rutrum lacus sit amet sem convallis, ut interdum dolor vestibulum.</p>
<p>Tum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. In iaculis pharetra odio, sit amet consectetur elit facilisis ac. Praesent eget tristique ipsum. Donec malesuada bibendum lacinia. Praesent non purus sodales, pulvinar mi vitae, tincidunt leo. Phasellus vitae elit ut nisl semper fringilla id rutrum dolor. Donec a massa adipiscing, cursus risus vitae, porttitor tortor. Nullam sagittis est sapien, sit amet pharetra turpis imperdiet vel. Etiam sit amet ligula pretium, vulputate eros ac, bibendum velit. Aenean convallis ante purus, ac bibendum orci laoreet ac. Donec a convallis mauris. Nulla non lacus non ipsum pretium tempor. In hac habitasse platea dictumst. Aenean at ipsum vulputate, sagittis dui ut, pharetra neque. Nam eget sodales orci. Aliquam pharetra nunc at nisl pellentesque, nec fringilla enim iaculis.</p>
</div>
</body>
</html>
I've got my problem solved by placing:
<script>
var mn = $(".main-nav");
mns = "main-nav-scrolled";
hdr = $('header').height();
$(window).scroll(function() {
if( $(this).scrollTop() > hdr ) {
mn.addClass(mns);
} else {
mn.removeClass(mns);
}
});
</script>
at the end of the document, before closing </body> tag.
I am trying to set vertical scroll bar to the div2 to replace the default browser vertical scroll bar.
.div1 {
height: 200px;
}
.div2 {
overflow-y: auto;
height: 500px;
}
<div id='container' style="height:100%">
<div class='div1'>
div1 content
</div>
<div class='div2'>
div2 content
</div>
</div>
With the above style, document is left with blank space at the bottom since height of div2 is not exactly occupying the entire document height. How do I fix that?
The steps to achieve what you want are:
Set both html's and body's margin and padding to 0.
Set the header's height to the fixed height you want: in your case, 200px.
Set the .main's height to 100% of the viewport less the header height: calc(100vh - 200px).
Set the .main's overflow-y to auto.
Create a section into the .main, and set the margin you want to show your content (optional).
And then, we're done! Take a look at the example below (if you want to test it in a better way, click on the Full Page button, and then play with your window's resizing etc):
html,
body {
overflow: hidden;
padding: 0;
margin: 0;
}
header {
height: 120px;
background-color: blue;
}
div.main {
height: calc(100vh - 120px);
background-color: red;
overflow-y: auto;
}
div.main > section {
margin: 10px;
}
div.main > div > p {
text-align: justify;
}
<header>
</header>
<div class="main">
<section>
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nunc tincidunt enim sit amet diam bibendum, ut rhoncus est molestie. Ut vulputate egestas mauris, eget ultricies tellus aliquet nec. Mauris nec neque et lorem volutpat feugiat eget sit amet
erat. Nullam luctus ultricies augue ut cursus. Mauris pulvinar velit at venenatis semper. Quisque non dolor ante. Nulla tempus id turpis et placerat. Interdum et malesuada fames ac ante ipsum primis in faucibus. Vestibulum justo elit, rhoncus vitae
massa non, condimentum ornare quam. Duis sit amet orci a risus mollis gravida et quis augue. Donec sed felis ante. Vestibulum rutrum non dolor quis finibus. Vestibulum ultricies leo eget mi elementum, vel vestibulum felis maximus. Donec congue lorem
vel ante mattis, eu luctus magna finibus. Donec sit amet dui quam.
</p>
<p>
In ullamcorper, nibh eget venenatis imperdiet, augue ante porttitor mauris, nec scelerisque tortor nisi eu arcu. Phasellus libero ligula, eleifend a lobortis in, cursus in tellus. Morbi volutpat, sem a dignissim venenatis, velit nulla vehicula sem, ut
fermentum augue eros sit amet nisi. Vivamus eget ex id turpis scelerisque lobortis sed sed arcu. Nulla facilisi. Curabitur hendrerit iaculis justo, at iaculis est facilisis sit amet. Donec sem tellus, posuere et metus id, consectetur vehicula sapien.
Ut eros quam, tempor vitae quam sed, efficitur faucibus sapien. Mauris varius velit orci, sit amet fermentum neque auctor ac. Nullam pretium sed urna et pellentesque.
</p>
<p>
Nunc id odio ligula. Sed ut dolor vitae sem fringilla condimentum. Sed venenatis lacus a magna egestas, nec volutpat quam ullamcorper. Maecenas volutpat eu magna nec ultrices. In egestas, risus id porta condimentum, odio urna ultricies mi, ut elementum
magna tortor quis eros. Sed a hendrerit felis. Curabitur id sem consectetur, luctus velit in, sollicitudin elit. Proin ac commodo tortor. Proin imperdiet id massa at sollicitudin. Pellentesque enim arcu, venenatis ut dictum et, ornare at tortor.
Donec et urna nec metus rhoncus auctor. Nunc id nisi nec sem condimentum vehicula a in arcu.
</p>
<p>
Proin eleifend sem massa, at auctor eros porta congue. Aliquam nec aliquet justo, at cursus ipsum. Cras justo leo, varius vel accumsan eget, sagittis sit amet lorem. Donec pulvinar ante ut efficitur eleifend. Duis tincidunt metus non nunc accumsan, vel
accumsan velit rhoncus. Nunc arcu magna, sollicitudin non urna in, pellentesque dignissim eros. Nam placerat sodales rutrum. Sed quis placerat leo. Nunc porttitor nisi nunc, in feugiat dolor accumsan nec. Aliquam gravida diam ac tempor sodales.
Ut in sapien gravida odio molestie vehicula sed vel nulla. Integer sed ipsum semper, auctor massa eget, viverra justo. Nullam mattis suscipit lorem vel mattis. Morbi non aliquet nunc. In hac habitasse platea dictumst.
</p>
<p>
Pellentesque dapibus sapien quis congue porta. Maecenas faucibus ex nisi, in varius risus imperdiet ac. Aliquam tristique egestas ligula, sed vestibulum lacus mollis vel. Nunc non ante ut quam placerat suscipit. Lorem ipsum dolor sit amet, consectetur
adipiscing elit. In a viverra augue, a dignissim justo. Aliquam volutpat nibh ut tellus interdum suscipit. Praesent mi sem, mollis in libero vel, pretium accumsan ex. Nullam gravida diam quis semper faucibus. Nullam cursus felis dolor, sed egestas
ex lobortis et. Vivamus at maximus felis, vel posuere purus. Quisque pellentesque risus nec posuere suscipit. Aliquam eleifend tempus ante, vel vehicula nunc facilisis quis. Mauris lacinia, felis at ultrices luctus, lacus nisl molestie neque, et
varius urna velit at massa. Nulla facilisi.
</p>
</section>
</div>
I'm not absolutely sure what you're trying to do but try adding this to your css and see if it fixes it.
html, body { height: 100%; }
Try this. The border on div1 and div2 is just to show the height of the div. Feel free to remove it ;)
#container {
height: 100%;
position: absolute;
}
.div1 {
height: 200px;
position: relative;
border: 2px solid yellow;
}
.div2 {
overflow-y: auto;
position: relative;
height: 100%;
border: 2px solid red;
}
<div id='container' style="height:100%">
<div class='div1'>
div1 content
</div>
<div class='div2'>
div2 content
</div>
</div>
The code can already scroll to the bottom after a submission, but the scroll bar does not update when there is a page update.
Here is how I want the scrollbar to behave:
1) The scroll bar starts at the bottom of the div.
2) The scroll bar scrolls to the bottom of the div only if you are at the bottom of the div before the content in the php file is updated.
3) The scroll bar does not scroll to the bottom of the div if you are not at the bottom of the div before an update was made to the content in the php file.
I searched Google and here for a method to get this to work, but what I have found does not work for me in my case.
Here's the code for the div:
<div id="div1" style="position: absolute; width: 70%; height: 80%; overflow-y: auto; right: 0px; top: 0px;" >
<?php include ('content.php'); ?>
</div>
And here's the code for the javascript:
$(document).ready(function() {
$('#msg').ajaxForm({
target: '#message',
success: function() {
$("#msg")[0].reset();
$("#div1").animate({ scrollTop: $("#div1")[0].scrollHeight}, 1000);
$('#message').fadeIn('slow');
}
});
});
To detect that the scroll bar is at the bottom you can use the following
function isScrolledToBottom(el) {
return el.scrollTop == el.scrollHeight - el.clientHeight;
}
Here's an example where
Div starts scrolled down
When content is added, it checks if the div was scrolled all the way down before updating content
If it was scrolled to the bottom, it scrolls it again after updating
var div = document.getElementById('content');
// Set it to go the bottom initially
scrollToBottom(div);
document.querySelector('button').addEventListener('click', function() {
var wasAtBottom = isScrolledToBottom(div);
var scrambledText = div.innerHTML.split('').sort(function() {
return Math.random() - .5
}).join('');
div.appendChild(document.createTextNode(scrambledText));
if (wasAtBottom) {
scrollToBottom(div);
}
});
function isScrolledToBottom(el) {
return el.scrollTop == el.scrollHeight - el.clientHeight;
}
function scrollToBottom(el) {
el.scrollTop = el.scrollHeight - el.clientHeight;
}
#content {
height: 150px;
overflow: scroll;
}
<div id="content"> Lorem ipsum dolor sit amet, consectetur adipiscing elit. Proin luctus imperdiet venenatis. Etiam lorem nisi, ullamcorper nec neque non, ultrices elementum lectus. Ut dapibus venenatis quam sit amet imperdiet. Proin scelerisque, nunc vitae ultricies aliquam, diam ligula venenatis purus, id egestas elit turpis sit amet velit. Suspendisse facilisis vel arcu eget hendrerit. Donec non nunc aliquam, finibus ante vitae, venenatis dolor. Suspendisse pulvinar fermentum rhoncus. Proin pulvinar lectus et purus consectetur rutrum. Phasellus rutrum dolor risus, non consectetur erat posuere eget. Etiam viverra congue laoreet. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Donec aliquet ullamcorper finibus. Nulla ac vehicula risus. Phasellus nec fermentum quam. Donec blandit ornare ipsum ut dignissim. Etiam nec velit maximus, mollis nibh id, elementum nisi. Donec arcu nisi, sollicitudin sit amet metus sed, aliquet convallis eros. Sed lacus metus, aliquet sed sodales vitae, rutrum sollicitudin dolor. Nunc dictum, mi id egestas luctus, mi erat finibus enim, a imperdiet orci est ac elit. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Suspendisse potenti. Sed dignissim viverra finibus. Ut quis nulla a sapien bibendum sodales at ut nunc. Etiam volutpat ante varius tellus vulputate blandit. Aliquam turpis purus, efficitur vel lacus imperdiet, viverra auctor nisl. Aenean nunc est, tempus nec tincidunt in, malesuada in mauris. Nam dui risus, maximus et placerat in, elementum tristique leo. Fusce quis viverra enim. Curabitur congue fringilla accumsan. Curabitur vehicula aliquet malesuada. Aliquam pharetra ante vel nulla elementum, sit amet auctor mi porttitor. Mauris id varius leo. Vestibulum ac dolor id ligula iaculis aliquam. Donec porta euismod quam, eu sollicitudin nisi interdum egestas. Vestibulum et ligula velit. Nulla vel iaculis purus. Integer et est ut ipsum fringilla rhoncus. Aliquam auctor eu arcu rhoncus maximus. Sed vulputate, ipsum nec tempus sodales, neque leo hendrerit elit, a faucibus nisl ex nec lorem. Praesent varius dictum felis, sed sollicitudin diam tempor vitae. Mauris tempus justo non egestas mollis. Etiam congue odio eget velit vulputate, sit amet pharetra nulla faucibus. Cras a lorem sed ante imperdiet dapibus id blandit risus. Pellentesque nec tincidunt lacus.</div>
<button>Add content</button>
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.