Make div stick to top of page after scrolling past another div? - javascript

<div id="header"></div>
<div id="sticky"></div>
<div id="section"></div>
<div id="footer"></div>
<style>
body { margin: 0px; background-color: #e3e3e3; }
#header { background-color: #cb5454; height: 140px; }
#sticky { background-color: #546bcb; height: 70px; }
#section { height: 1500px; }
#footer { background-color: #cb5454; height: 140px; }
</style>
Here is my code: http://jsfiddle.net/uaqh018d/
I want #sticky to stick to the top of the page after scrolling past #header. I also want it hidden until stuck. And then of course have it unstick+hide again after scrolling back up to #header.
How can I achieve this?

I would recommend adding a class to #sticky when it's ready to be fixed to the top of the screen, and then removing that class when you want to 'unstick' it. Then you can manipulate that class in CSS.
e.g. for a class fixed you'd put the following in your CSS:
#sticky {
display: none;
background-color: #546bcb;
height: 70px;
}
#sticky.fixed {
display: block;
position: fixed;
top: 0;
width: 100%;
}
And then your jQuery would look like this:
$(window).scroll(function() {
var distanceFromTop = $(this).scrollTop();
if (distanceFromTop >= $('#header').height()) {
$('#sticky').addClass('fixed');
} else {
$('#sticky').removeClass('fixed');
}
});
Here's an updated FIDDLE
I might also recommend some jQuery fade or slide effects (see the fiddle).

You can use position: fixed and in js detect when user scroll like this:
$(document).scroll(function() {
//detect when user scroll to top and set position to relative else sets position to fixed
$("#sticky").css({
"top": "0",
"position": $(this).scrollTop() > 140 ? "fixed" : "relative"
});
});
body {
margin: 0px;
background-color: #e3e3e3;
}
#header {
background-color: #cb5454;
height: 140px;
}
#sticky {
background-color: #546bcb;
height: 70px;
width: 100%;
position: fixed;
}
#section {
height: 1500px;
}
#footer {
background-color: #cb5454;
height: 140px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="header"></div>
<div id="sticky"></div>
<div id="section"></div>
<div id="footer"></div>
References
.scroll()

In my case, the div I wanted to be sticky was inside of another div (ie. not stuck to the page, but in another fixed div on the side of the page). Here's my adaptation of #bowhart's answer to solving this problem given a React component (sticky_adapter.js):
module.exports.makeItSticky = function(thisReactComponent, parentScrollNode = window) {
const thisNode = $(ReactDOM.findDOMNode(thisReactComponent));
const position = thisNode.position();
// Uncomment for verbose logging
//console.log("Initial position: " + UIUtils.stringify(position));
const scrollContainer = $(parentScrollNode);
scrollContainer.scroll(() => {
const distanceFromTop = scrollContainer.scrollTop();
// Uncomment for verbose logging
//console.log("ScrollTop: " + distanceFromTop);
if (distanceFromTop > position.top) {
thisNode.addClass("stick-to-top");
} else {
thisNode.removeClass("stick-to-top");
}
});
};
Now, to make any React component sticky, I just add to the class:
componentDidMount() {
StickyAdapter.makeItSticky(this, ".some-other-div-which-is-the-container");
}
Finally, the css for the sticky class:
.stick-to-top {
display: block;
position: sticky;
top: 0;
z-index: 10;
}

Hey this is and old question but for new visitors I think u just need to add this css code to #sticky:
#sticky { position:sticky;top:0; }
and no need for javascript.
sticky toggles between relative and fixed, depending on the scroll position.
and don't forget that, the parent also should not have overflow property

Related

Pure CSS overlay scrolling

using only css and html, is it possible to scroll away the inner div (overlay red div) completely before scrolling down the rest of the page? Essentially, wondering if overlay scrolling while freezing the behind div is possible in only css? Then once the red div is gone, unfreeze the background scrolling and continue on. Similar to this site here: https://humaan.com/ . Or would some sort of JavaScript need to be used?
.headervideo{background-color:blue; width:100%; height:900px;}
.headerbreak{width:100%; height:300px;}
.headervideo #inner-box {
background-color: red;
height: 90%;
width: 100%;
}
<div class="headervideo">
<div id="inner-box"></div>
</div>
<div class="headerbreak">
<div>
position:sticky can approximate this:
.headervideo {
background: url(https://picsum.photos/id/1064/800/800) center/cover;
height: 100vh;
position: relative;
z-index: 2;
}
.nextsection {
background: url(https://picsum.photos/id/107/800/800) center/cover;
height: 100vh;
margin-top: -100vh;
position: sticky;
top: 0;
}
.container {
height:200vh;
}
body {
margin: 0;
}
<div class="container">
<div class="headervideo"></div>
<div class="nextsection"></div>
</div>
<div style="height:150vh"> more content later </div>
With CSS, you could use the hover event to detect a certain scroll position (e.g. on something just after the red div), but this would not work on touch only devices like mobile phones. It also wouldn't be reliable, as the cursor could be anywhere on the screen.
Using JavaScript to detect scroll position would be necessary. However, you could use the JavaScript only to add a class at different scroll positions and then do the rest with CSS. Here's a simple example:
var red = document.querySelector('#inner-box');
var begin = red.scrollTop;
var end = begin + red.clientHeight;
console.log(begin)
document.body.classList.add('in');
window.addEventListener("scroll", (event) => {
if(this.scrollY < begin) {
document.body.classList.add('before');
document.body.classList.remove('after');
document.body.classList.remove('in');
} else if(end < this.scrollY) {
document.body.classList.remove('before');
document.body.classList.add('after');
document.body.classList.remove('in');
} else {
document.body.classList.remove('before');
document.body.classList.remove('after');
document.body.classList.add('in');
};
});
.headervideo {
background-color: blue;
width: 100%;
height: 900px;
}
.headerbreak {
width: 100%;
height: 300px;
}
.headervideo #inner-box {
background-color: red;
height: 90%;
width: 100%;
}
body {
}
body.before {
background-color: lightgreen;
}
body.in {
background-color: lightpink;
}
body.after {
background-color: lightblue;
}
<body>
<div class="headervideo">
<div id="inner-box"></div>
</div>
<div class="headerbreak">
<div>
</body>

Using pure CSS, make a div centered until it runs into sidebar from resizing the window?

I want to create a website with a single fixed-width centered column and an additional fixed-width sidebar that is position: fixed on the left. When the window is large, this works perfectly, but when I resize the window, they begin to overlap when there's plenty of room left on the right side of the window. For example:
I'd like the center div to be positioned in the center until it runs into the sidebar, at which point I'd like it to have a more fluid responsive design, where the sidebar starts to push the div to the right as you resize the window. For example:
The only solution I'm aware of is something like this (using the jQuery resize event and adding a class to the center column when the window resizes small enough):
var SMALL_WINDOW_SIZE = 560;
function checkWindowSize() {
var $content = $("#content");
if ($(this).width() < SMALL_WINDOW_SIZE && !$content.hasClass("smallWindow")) {
$content.addClass("smallWindow");
} else if ($(this).width() >= SMALL_WINDOW_SIZE && $content.hasClass("smallWindow")) {
$content.removeClass("smallWindow");
}
}
$(document).ready(function() {
checkWindowSize();
});
$(window).resize(function() {
checkWindowSize();
});
#sidebar {
background: orange;
width: 100px;
height: 200px;
position: fixed;
top: 10px;
left: 10px;
}
#content {
background: blue;
width: 300px;
height: 350px;
margin: 0px auto;
}
.smallWindow {
float: left;
margin-left: 120px !important;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div id='sidebar'></div>
<div id="content"></div>
I can't help but feel there should be a pure CSS solution or one that uses less or more elegant JavaScript. Is there such a thing?
This isn't by any means the best way of achieving the desired effect with CSS, but it's the methodology behind using CSS media queries to adapt layout that I want to convey.
Obviously if this meets your needs, you'll want to adjust the numbers/widths to suit your case.
*, :before, :after{
box-sizing: border-box;
}
body {
margin: 0;
}
.wrapper {
position: relative;
padding: 20px;
}
.sidebar, .main {
padding: 20px
}
.sidebar {
position: fixed;
top: 20px;
left: 20px;
width: 200px;
background: goldenrod;
color: white;
height: 50vh;
}
.main {
margin-left: 220px;
background: mediumblue;
color: white;
height: 200vh;
}
#media (min-width: 1050px){
.main{
margin: 0 220px 0 220px;
}
}
<div class="wrapper">
<div class="sidebar">
Sidebar
</div>
<div class="main">
Main
</div>
</div>
ยป JSBin

jQuery scroll back to top

According to this post i asked how to make a scroll method wich shows a element, scrolls to it and hide the element where i came from.
I improved that code, and it works.
But when I try to do this backwards, so from the second screen to the first screen again. Its not working. Its only scrolling to the top of the #content screen...
How does this come?
Here's a jsFiddle:
In order to achieve the desired effect you ll need to change up your markup/css and js logic a bit, as of now you are hiding the top element so once the scroll is done the bottom element's offset top = 0.
First change is to wrap your html in a <div> we ll give that div an id of #container.
Second of all we need to set the container's position to absolute so that we can slide it up and down on button click.
The css :
html,body {
height: 100%;
width: 100%;
margin: 0;
padding: 0;
overflow:hidden;
}
#page1 {
height: 100%;
width: 100%;
}
#content {
height: 100%;
width: 100%;
overflow-y:scroll;
}
#exploreBtn {
height: 50px;
width: 50px;
background-color: red;
}
#goBack {
position: fixed;
bottom: 5%;
right: 5%;
height: 50px;
width: 50px;
background-color: purple;
}
#container {
position:absolute;
width:100%;
height:100%;
}
And finally we need to change up the js:
$(document).ready(function () {
$('#exploreBtn').on('click', function () {
showScrollHide('#content', '#page1');
});
$('#goBack').on('click', function () {
showScrollHide('#page1', '#content');
});
});
function showScrollHide(element, hide) {
var _ele = $(element),
_container = $('#container'),
_ele_top = _ele.offset().top;
if(_ele_top < 0)
_ele_top = 0;
console.log(_ele_top);
_ele.fadeIn(500, function () {
_container.stop().animate({
top: - _ele_top
}, 1000);
});
}
We get the desired effect, needs a bit of tweaking but you get the general picture.
Hope i helped.
The fiddle
put this in clck handler of the back to top button:
$('html').scrollTop(0);

Dynamic float menu issue

I want to make the menu fixed on top when window scroll down over 160 pixel, but if the body content is too short, it will become an infinite loop, because if I scroll down over 160 pixel, menu will become fixed which means scroll height will turn to under 160 pixel, so script will make the menu relative back, how to solve this.
Demo
HTML
<div id="header">header</div>
<div id="content">content</div>
JavaScript
$(window).on('scroll', function() {
var scroll = $(window).scrollTop();
if (scroll > 160) {
$('#header').css('position', 'fixed');
} else {
$('#header').css('position', 'relative');
}
});
CSS
body {
margin: 0;
padding: 0;
}
#header {
width: 100%;
height: 60px;
background: black;
color: yellow;
position: relative;
padding: 6px;
}
#content {
width: 100%;
height: 780px;
background: gray;
}
when adding position fixed to menu, add also paddin-top for content (padding-top value equals header height + header top and bottom padding)
JS:
$(window).on('scroll', function() {
var scroll = $(window).scrollTop();
if (scroll > 160) {
$('#content').css('padding-top', '72px');
$('#header').css('position', 'fixed');
} else {
$('#content').css('padding-top', '0');
$('#header').css('position', 'relative');
}
});
fiddle
you do not need any javascript here...so remove all js... and edit your css:
#header {
width: 100%;
height: 60px;
background: black;
color: yellow;
position: fixed; /* make menu header always fixed */
padding: 6px;
top:0px;
}
#content {
width: 100%;
height: 780px;
margin-top:72px; /* margin top 72px because of header height is 60px + pedding 6px*2 */
background: gray;
}

Moving divs with javascript

This is my problem, I have a div and inside 2 divs, one is centered and the other one is fixed on the left, the problem is when I resize the screen the centered div overlaps the fixed one, what I wanted to do is detect when the centered div overlaps the other div and change its left value with javascript, but is not working, any ideas?
This is my design:
<div id="content-wrap">
<div id="content">
</div>
<div id="leftbar">
</div>
</div>
and the CSS:
#content-wrap
{
clear: both;
float: left;
width: 100%;
}
#content
{
text-align: left;
padding: 0;
margin: 0 auto;
height: 470px;
width: 760px;
overflow: auto;
}
#leftbar
{
background-color: transparent;
width: 200px;
height: 470px;
position: absolute;
top: 185px;
left: 50px;
}
and this is the javascript code:
window.onload = function Centrar() {
var leftBar = $get("leftbar");
if (leftBar != null) {
var content = $get("content");
var size = leftBar.offsetLeft + leftBar.offsetWidth;
if (content.offsetLeft < size) {
content.style.left = size + 20 + 'px';
}
}
}
Thanks in advance for any help.
The easiest fix would be to apply a min-width to your #content-wrap container that prevented the overlap from occurring:
#content-wrap {
clear: both;
float: left;
width: 100%;
/* #leftbar width x 2 + #content width */
min-width: 1160px;
}
However, if you want to use Javascript, you'll need to attach the code to the window load and resize events:
$(window).bind('load resize', function() {
var content = $('#content');
var leftbar = $('#leftbar');
// get the right edge of the #leftbar
var leftbarEdge = leftbar.width() + leftbar.offset().left;
// check if an overlap has occured and adjust #content left position if yes
if (leftbarEdge > content.offset().left) {
content.css({
left: leftbarEdge - content.offset().left
});
}
});
The last change you'll need to apply to get this working is to set #content to position: relative in the CSS so it respects the left property you're setting with Javascript:
#content {
position: relative;
/* remaining css */
}
You can see it in action here.

Categories

Resources