Sticky sidebar from bottom during scrolling - javascript

I'm planning to recreate the Medium.com like sidebar. This is what I have now but it's far from over.
Open the JSFiddle below to understand better; I am looking to do the following:
When you scroll down, it suddenly sticks to the bottom. How do I make it stick gradually as you scroll?
Because it uses position: fixed, it moves towards the right side without respecting the layout. How do I fix this?
When you scroll up and there's less space, it overlaps with the header as shown in the screenshot. Again, most likely because position: fixed is used.
How do I fix this? I know there's sticky-kit that does the work but I can't use any plugin.
HTML:
<div class="container">
<div class="row">
<div class="col-xs-12">
Header and Menu is placed here.
<hr />
</div>
<div class="col-xs-8">
<p>This is the main body which the user would be scrolling infinitely as more data gets loaded on scroll.</p>
</div>
<div class="col-xs-4">
<div id="sidebar">
<p>
This is the sidebar which I want to stop when it reaches the bottom like the one shown in medium dot com
</p>
</div>
</div>
</div>
</div>
Javascript:
function scrollCheck() {
var $right = $('#sidebar'),
scrollTop = $(window).scrollTop(),
windowHeight = $(window).height(),
docHeight = $(document).height(),
rightHeight = $right.height(),
distanceToTop = rightHeight - windowHeight,
distanceToBottom = scrollTop + windowHeight - docHeight;
if (scrollTop > distanceToTop) {
$right.css({
'position': 'fixed',
'bottom': (scrollTop + windowHeight > docHeight ? distanceToBottom + 'px' : '0px')
});
}
else {
$right.css({
'position': 'relative',
'bottom': 'auto'
});
}
}
$(window).bind('scroll', scrollCheck);
JSFIDDLE

I'll answer what questions of yours I could. Here is the edited Fiddle first.
As for your questions:
The sudden sticking to the bottom is caused because the element isn't the full length of the page so sticking it to the bottom with a fixed position will cause it to jump there. Whereas with the change I made so it sticks to the top there won't have this jump, as the element is at the top of the screen when scrolling so it can be discreetly fixed there.
This was because the element didn't have a fixed width and setting position: fixed; means that the elements width is no longer set by the parent, but the view port. So it expands to fill all the width in the view port it can.
This was happening because the position: fixed; was never removed when scrolling back above the elements original position, the updated if statement in the Js now removes the class with position: fixed; when scrolling above its original location.
A more detailed look into what I changed.
I added a CSS class so .toggleClass could be used to make the function cleaner.
.docked-sidebar {
position: fixed;
top: 0;
}
I also changed the conditions for the if statement so that they worked. Using .offset().top; to get the distance between the sidebar and the top of the page, while removing most of the other variables as they weren't needed. Finally I created bool variable(isDocked) so that the same condition isn't triggered multiple times.
var $right = $('#sidebar'),
isDocked = false,
initOffsetTop = $right.offset().top;
function scrollCheck() {
var scrollTop = $(window).scrollTop(),
offsetTop = $right.offset().top;
if (!isDocked && ((offsetTop - scrollTop) < 0)) {
$right.toggleClass("docked-sidebar");
isDocked = true;
} else if (isDocked && scrollTop <= initOffsetTop) {
$right.toggleClass("docked-sidebar");
isDocked = false;
}
}
For sticking to the bottom and then to the top exactly like the example website I recommend checking this question.

Related

Changing div position to fixed with javascript attaches the div to document not viewport

I am looking for a way to determine if any part of a div is touching the top of the viewport and fix an item in that div to the top of the viewport using vanilla javascript.
I have been able to sort out how to determine if the div is touching the top of the viewport and trigger changes to the div's style. But for some reason when I change the div's position: absolute to position: fixed the div fixes to the top of the document, not to the top of the viewport, hence is not visible.
My js
function touchTop() {
var div = $('itin');
var rect = div.getBoundingClientRect();
var y = rect.top;
var h = rect.bottom;
if ((y < 0) && (h > 0)) {
document.getElementById('seemore').style.position = 'fixed';
document.getElementById('seemore').style.top = '45%';
} else {
document.getElementById('seemore').style.position = 'absolute';
document.getElementById('seemore').style.top = '66px';
}
}
window.addEventListener('scroll', touchTop);
The basic div HTML
<div id="itin" class="container">
<div class="sp20"></div>
<div class="text rgt">
<h3>your daily adventures</h3>
<p>blah blah blah</p>
</div>
<div id="seemore" class="ghstbtn">See More</div>
</div>
And the basic initial CSS
#seemore {
width: auto;
position: absolute;
top: 66px;
right: 20px;
}
To clarify further: My problem that needs solving is that when javascript changes the style.position to fixed the #seemore div gets positioned such that the 'top' value is measured from the top of the document, not from the top of the viewport. So basically not visible in the viewport.
If I understand you correctly, I think your problem lays here:
if ((y < 0) && (h > 0))
When the container div hits the top of the document, position to "seemore" is set to fixed, but as fast as the bottom of the div hits the top of the document,
"h === 0" and the position is again set to absolute.
Try this.
const seeMore = document.getElementById('seemore');
const div = document.getElementById('itin');
window.addEventListener('scroll', checkBoundries);
function checkBoundries() {
var rect = div.getBoundingClientRect();
var y = rect.top;
var h = rect.bottom;
if (y < 0) {
seeMore.style.position = 'fixed';
seeMore.style.top = '45%';
} else {
seeMore.style.position = 'absolute';
seeMore.style.top = '66px';
}
}
Turns out to be related to a filter applied to a parent of a parent of a parent of a ....
Found some old questions regarding issues with transformations and position:fixed dating back some 5 to 7 years ago. And even though many mentioned filing issue reports with the browser makers, it seems the problem has never been addressed and resolved. One comment mentioned filters could also cause the issue.
Moved the filter to a separate class which is now added and removed, rather than applying the filter directly to the div. And everything works as expected.

Set div to fixed until it comes into contact with other element where it becomes absolute. Won't revert back to fixed when scrolling back up

I'm having some trouble adding a sticky on scroll "Add to Cart" area to a product page.
So far I'm able to make the selected element become position: fixed from a certain point while scrolling until it reaches a 'cutoff point' so to speak, where it becomes position: absolute.
I also have a rule written to remove the position styling when I scroll above the 'starting point' for position: fixed. All of these are written inside one function which fires on $(document).scroll(). I'll post my code below.
The rules I've written seem to be working fine except for one specific thing. When I scroll down, the element becomes fixed. When the fixed element reaches the 'cutoff point' it switches to position: absolute and stays there when I continue scrolling. This is what I want.
The problem is when I start scrolling back up past the 'cutoff point' the element's positioning doesn't switch back to position: fixed. It stays position: absolute until I reach the top of the page where the styling is removed. I can then scroll down again and it will start all over again, fixed > absolute > not reverting back to fixed on scroll up.
function checkOffset() {
var div1 = $(".ProductMain");
var div2 = $(".SideRelatedProducts");
var div3 = $("#cssmenu");
var div1_top = div1.offset().top;
var div2_top = div2.offset().top;
var div3_top = div3.offset().top;
var div1_bottom = div1_top + div1.height();
var div2_bottom = div2_top + div2.height();
var div3_bottom = div3_top + div3.height();
// This is what removes styling assigned from scrolling, when element gets back to top of page
if (div1_bottom >= div3_bottom && $(window).width() > 900) {
$('.ProductMain').css({
'position': 'absolute',
'top': 'auto',
'bottom': '55px'
});
console.log('ABSOLUTE');
}
// This is what removes styling assigned from scrolling, when element gets back to top of page
if ($(document).scrollTop() > $('.main').offset().top + 20 && $(document).scrollTop() + div1.height() < (div2_top + 75) && div1_bottom < div3_bottom && $(window).width() > 900) {
$('.ProductMain').css({
'position': 'fixed',
'top': '60px',
'bottom': 'auto'
}); // restore when you scroll up
console.log('FIXED');
}
// This is what removes styling assigned from scrolling, when element gets back to top of page
if($(document).scrollTop() < $('.main').offset().top && $(document).scrollTop() + window.innerHeight < div2_top || $(window).width() < 900) {
$('.ProductMain').removeAttr('style');
}
}
$(document).scroll(function() {
checkOffset();
});
Thanks for your help!
This seems to be answered already. Please try this answer here:
Using jQuery to keep scrolling object within visible window

make div scoll untill it reaches top of page then fixed

let's get straight to the point:
My code looks like the following:
<div id="keep_up">
<div id="thread_menu">
<div id="new_thread">
</div>
</div>
</div>
And my css:
#keep_up {
position: fixed;
width: 13%;
}
#thread_menu{
height: 80vh;
width: 100%;
float: left;
position: relative;
}
Now i use this for a forum. and this is basically to show the active and new threads on the side of the screen.
However. When watching a thread, the header disappears (Wich makes sense because we are scrolling down).
but i want the thread menu to stay on my side (So that it is always visible). In this case that is happening because my keep_up div has position: fixed. But i only see half of the thread menu becuase it is too long and won't scroll up.
My question:
I want the thread menu to scroll up, untill it reaches the top of my window. From then on i want it to stay there.
How do i do this?
I saw a few examples but none of them worked for me.
EDIT: Code i tried:
<script src="jquery.min.js">
$(window).scroll(function () {
var margin = null;
$(window).on("scroll", function () {
var scrollHeight = $(document).height(),
scrollTop = $(window).scrollTop(),
offsetBottom = 110, // Offset depending on the height of the footer
offsetTop = 100, // Offset depending on the height of the header
positionTop = $(".keep_up").offset().top,
affix;
if (margin != null && (scrollTop + margin <= positionTop)) {
// The sidebar has reached the bottom and is still on the bottom
affix = false;
} else if (positionTop + $(".keep_up").height() >= scrollHeight - offsetBottom) {
// The sidebar has reached the bottom
affix = 'bottom';
} else if (scrollTop <= offsetTop) {
// The sidebar has reached the top
affix = 'top';
} else {
// The sidebar is midway
affix = false;
}
// If the sidebar hasnot changed his state, return;
if ($(".keep_up").hasClass('at' + (affix ? '-' + affix : ''))) return;
if (affix == 'bottom') {
margin = positionTop - scrollTop;
} else {
margin = null;
}
// If the related class is added to the div
$(".keep_up").removeClass('at at-top at-bottom').addClass('at' + (affix ? '-' + affix : ''))
});
});
</script>
And the CSS:
.keep_up{
/*position: fixed;*/
width: 13%;
}
.keep_up.at {
top: 1px;
position: fixed;
}
.keep_up.at-top{
}
.keep_up.at-bottom {
top: 438px;
position: absolute;
}
modify this on HTML:
<div id="prevent"></div>
<div id="keep_up" data-spy="affix" data-offset-top="200">
Add this CSS:
.affix{position: fixed !important; top:0px; z-index:999;}
.affixpatch{margin-top:100px !important;}
this will fix the div when you scroll down 200px. Change data-offset-top value to reach it on different break point.
.affixpatch is a class that will be loaded with next jquery function. it prevents to hide content behind top fixed div. Change margin-top to another value if this don't solves the "hide content" problem that always generate affixing divs.
<script>
$(function() {
//caches a jQuery object containing the header element
var header = $(".affix");
$(window).scroll(function() {
var scroll = $(window).scrollTop();
if (scroll >= 200) {
$('#prevent').addClass("affixpatch");
} else {
$('#prevent').removeClass("affixpatch");
}
});
});
</script>
Hope it helps. If not, you may have some class that rewrite or impede the correct function of this affix.
I've tested this hundreds of times, usually to fix navbars.
SCROLL:
Using overflow to scroll content:
#keep_up{
max-height:400px;
width: auto;
overflow:auto;}
This will scroll the content inside #keep_up div (or use it in another one)
NOTE: you must declare a fixed max height for this div. Set max-width only if you need.
You can use %, em, rem... no need to be px for fix the max witdth. (to get a responsive effect, use responsive measurements)
If I understand your scenario correctly, the way to do this might be to use jQuery (or native JS, but you've tagged jQuery so I'm assuming that's in play).
There's a plugin that handles this kind of thing: http://leafo.net/sticky-kit/
I'd suggest you look at the plugin source code to see how it works - an event handler function on $(window).scroll() which then toggles classes on your #thread_menu to fix it in place. To keep your code lightweight, you probably don't need everything the plugin provides.

Scrolling Two Divs Using JQuery/Javascript

Wrapper - Overflow Hidden
Div One: Sidebar
Div Two: Main Content
Div Two will have a normal scroll. Div One I wish to have no visible scroll however when you scroll Div One it scrolls Div Two.
Upon Div One's height hitting the bottom, it will no longer scroll and visa-versa for scrolling back up.
This will result in the sidebar always being visible at the side. Before you ask, I've tried all positioning types to get this to work resulting in many failed attempts.
My live demo can be seen here: http://rafflebananza.com/admin/newadmin.html#
Note I've tried to make a JSFiddle simplified but my maths does not seem to work in there the same. Please suggest whether I should fork all my page to there or whatnot for future visitors needing the same help.
Overview
Scrolling in the wrapper will scroll sidebar to point x only (x being the sidebars height) then stopping but will continue to allow the content to be scrolled. Visa-versa for scrolling back up.
Somewhat half way there...
var scrollTop = (window.pageYOffset !== undefined) ? window.pageYOffset : (document.documentElement || document.body.parentNode || document.body).scrollTop,
position = document.body.scrollTop;
function scrollD() {
var scroll = document.body.scrollTop;
if (scroll > position) {
// Scrolling Down Functions
} else {
// Scrolling Up Functions
}
position = scroll;
}
Updated the answer to match OPs requirements.
I downloaded your website in its current state and made the following changes to your code:
var scrollY = 0;
$(window).scroll(function() {
var sideNav = $('.SideNav'); // The side navigation
var wScrollY = $(this).scrollTop(); // Current scroll position of Window
var navHeight = sideNav.height(); // Height of the Navigation
var StageHeight = $(window).height() - 46; // The display space
if(sideNav.height() > StageHeight) { // Do the following if the side navigation is higher than the display space
var spaceLeft = sideNav.height() - StageHeight; // spaceLeft -> how many pixel left before fixing navigation when scrolling
if(scrollY < wScrollY) { // Scroll direction is down
if (wScrollY >= spaceLeft) // If scroll top > space left -> fixate navigation at the bottom, otherwise scroll with the content
sideNav.css({top:46-spaceLeft+wScrollY});
if (wScrollY <= 46) // Set top strict to 46. Sometimes there is white space left, caused by the scroll event.
sideNav.css({top:46});
} else { // Scroll direction is up
var sideNavTop;
if (sideNav.offset().top < 0) {
sideNavTop = Math.pow(sideNav.offset().top); // if top is negative, make it positive for comparison
} else {
sideNavTop = sideNav.offset().top;
}
if (sideNavTop > (46+wScrollY)) // Fixate the header if top of navigation appears
sideNav.css({top:46+wScrollY});
}
} else {
sideNav.css({top:46+wScrollY}); // Fixate always
}
scrollY = wScrollY;
});
This will let you scroll your side navigation up until its end. Then fixate. If you scroll up, it will still be fixated until your reach the point, where the navigation must scrolled back to its original position.
You can check the edited version here: http://pastebin.com/Zkx4pSKe
Just copy the raw code into a blank html page and try it out.
It's a bit messy and maybe not the best solution, but it works.
Ok, here you go:
var $sidebar = $('.sidebar'),
$window = $(window),
previousScroll = 0;
$window.on('scroll', function (e) {
if ($window.scrollTop() - previousScroll > 0) {
$sidebar.css({
'top': Math.max($window.scrollTop() + $window.height() - $sidebar.outerHeight(true), parseInt($sidebar.css('top'))) + 'px'
});
} else {
$sidebar.css({
'top': Math.min($window.scrollTop(), parseInt($sidebar.css('top'))) + 'px'
});
}
previousScroll = $window.scrollTop();
});
http://jsfiddle.net/7nwzcpqk/1/
i might have misunderstood your desired result incorrectly but you can see if this works for you :
.SideNav {
position: fixed; // you currently have this as position:absolute;
}
You don't need nor a wrapper element nor jQuery. I assume that you are using a wrapper because you want to have the top bar placed there. I think there is a better way to do it by using simply three divs.
The top bar has to be fixed (to be always visible) and of full width.
The side bar also has to be fixed (to be always visible) with a top margin of the height of the top bar.
The content needs just a left padding (width of side bar) and top padding (height of top bar).
Here is the example code (http://jsfiddle.net/zckfwL4p/):
HTML
<div id="top_bar"></div>
<div id="side_bar">links here</div>
<div id="content"></div>
CSS
body {
margin:0px;
padding:0px;
}
#side_bar {
width:50px;
position: fixed;
left:0px;
top:20px;
background-color:blue;
}
#top_bar {
position:fixed;
height:20px;
left:0px;
right:0px;
background-color:red;
}
#content {
position:relative;
padding-left:55px;
padding-top:25px;
}

jQuery - on window scroll run a function without any delay

I have an issue with a jquery function. You can see a working demo here - http://dev.sreejesh.in/menuissue/ . As you can see when the user scrolls down to the page, I have written a jQuery function(which will triger on scroll) to check scroll pixel. When the browser scrolls to a certain pixel(height of the sidemenu block), the Menu block will stay fixed & rest of the content scrolls as normal.
The functionality is working now, however the problem is menublocks makes a jumps when this function runs. I think this is because of the delay in running the function. Hope you guys have any nice trick to fix this.
I used an if/else function to check the scroll pixel, so when the scrolled pixel is greater than menublock height it will add a class "fixed" .
I use the following code.
HTML
<div id="globalwrapper">
<div id="menubar">
---- Menu List items-----
</div>
<div id="mainblock">
----Main content area----
</div>
</div>
jQuery
$(document).ready(function(){
$(window).scroll(function() {
adjustScroll();
});
});
function adjustScroll(){
var windowHeight = $(window).height();
var menublockHeight = $('#menubar').height();
var scrollValue = $(document).scrollTop();
var posValue = menublockHeight - windowHeight;
var menuStatus = $('#menubar').css('left');
$('#menubar').css('minHeight', windowHeight);
$('#menubar').css('height', menublockHeight);
console.log(menuStatus);
$(document).scroll(function() {
if(menuStatus == '0px') {
if(scrollValue > posValue){
$('#menubar').addClass('fixed');
$('#menubar').css('marginTop', -posValue);
}else {
$('#menubar').removeClass('fixed');
$('#menubar').css('marginTop', '0px');
}
}
});
}
I think only CSS can solve this issue, add this style:
#menubar{
position: fixed;
}
just test on Google Chrome,you can have a try.

Categories

Resources