make div scoll untill it reaches top of page then fixed - javascript

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.

Related

How to update sticky menu's CSS positioning on window resize

I've built a sticky navbar based on an example from W3 schools. It's working very well — except when I resize the window, the alignment of the nav menu to the page content is incorrect.
You'll see that I've got some code that finds the correct offset for left side of menu, by checking another element on the page. It then adds some left padding to align it properly. (Without this, the position:fixed value just sends the sticky nav to the far left of the page).
This works great on scroll! However, if the window is resized horizontally, that left padding value doesn't update.
I've tried a few iterations of $(window).resize but haven't been able to get it to work. I'm sure it's an easy line of code I'm just not figuring out. Thanks in advance!
setTimeout(function () {
// When the user scrolls the page, execute myFunction
window.onscroll = function() {myFunction()};
// Get the navbar
var navbar = document.getElementById("app");
// Get the offset position of the navbar
var sticky = $("#app").offset().top
// Find correct offset for left side of menu (by checking #title element)
var element = document.getElementById('title');
var leftPos = element.getBoundingClientRect().left + window.scrollX;
var roundLeft = (Math.round(leftPos)) - 5;
// Add the sticky class to the navbar when you reach its scroll position. Remove "sticky" when you leave the scroll position
function myFunction() {
if (window.pageYOffset >= sticky) {
navbar.classList.add("sticky")
navbar.style.cssText = "padding-left:" + roundLeft + "px!important";
} else {
navbar.classList.remove("sticky");
navbar.style.cssText = "padding-left:inherit";
}
}
}, 4000);
.sticky {
position: fixed;
top: 0;
width: 100%;
background: rgba(255, 255, 255, 0.99);
z-index: 9 !important;
max-width: none !important;
box-shadow: 0px 1px 10px #999;
}
(I'm using setTimeout because our Shiny app takes a few seconds to load and for the content to populate.)
You should use pure CSS solution with position: sticky
It does have acceptable percentage of browser support:
https://caniuse.com/#feat=css-sticky
Since it's just the styling, it may be fine to show it static in the old browsers.

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;
}

A cleaner way for a fixed div at bottom of the window but stays above the footer and triggers on page width

I've created a sticky bar to stay at the bottom of the window. As the user scrolls down to the bottom of the page the same bar will stay fixed until the footer shows, then removes its fixed position, temporarily, to stay above the footer until the user scrolls back up and it remains fixed again.
I only want to happen when the page is wider than 680px. Anything under that will keep the sticky bar in a default position (CSS: position:inherit).
This is the website: http://ttd.firefly-digital.co.uk
It works as expected. However, when I test on Chrome in Mac it triggers my CPU fan which suggests this not very efficient and with my limited JavaScript skills, wondered if there is a cleaner way to achieve this is?
This is the current js code:
$(window).scroll(function(event) {
var scroll = $(this).scrollTop();
var docHeight = $(document).height();
var windowHeight = $(window).height();
var footerHeight = $('.footer').height();
if(docHeight - (windowHeight + scroll) < footerHeight) {
$('.contact-bar').css({
bottom: footerHeight - (docHeight - (windowHeight + scroll))
});
} else {
$('.contact-bar').css({
bottom: 0
});
}
});
var windowWidth = $(window).width();
$(window).resize(function() {
windowWidth = $(window).width();
if(windowWidth > 680) {
$('.contact-bar').css({
position: "fixed"
});
} else {
$('.contact-bar').css({
position: "inherit"
});
}
});
CSS code
.contact-bar {
background: $contact-bar;
width: 100%;
height: 40px;
text-align: center;
position: fixed;
bottom: 0;
z-index: 10;
}
You can do it in reverse. Make it so that the bar, without position fixed, is above the footer without any JavaScript (incl. media queries). Than add a fixed class with position:fixed and bottom:0 that will be added accordingly. Like so:
.contact-bar.fixed { position:fixed; bottom:0; }
The jquery code that will trigger this, is as follows:
$(window).scroll(function (event) {
var windowTop = $(this).scrollTop();
if (windowTop >= $(".footer").offset().top) {
$(".contact-bar").addClass("fixed");
} else {
$(".contact-bar").removeClass("fixed");
}
});
Then add a few lines that the above code will only fire if the window width is > 680, either with jquery or pure javascript. For example with:
if ($(window).width() < 960) { // above function }
Do note I have not tested this, so please comment if it doesn't work. Credit: Preventing element from displaying on top of footer when using position:fixed
You better use classes to target your elements, at least to prevent jQuery from traversing the whole DOM using selectors appropriately which is good in performance.

Resize a div according to the window scrolling and the div min height

I'm trying to achieve this:
When users scroll page, i need a header that will be fixed, but before to stick it, this div should shrink to a certain height, and after that this div become fixed.
This is my attempt
As you can see, there are some strange behavior on shrinking, i think that my approach is not so right.
header.css("height", "-=" + (Math.abs(start - scrollTop)));
spacer.css("height", "-=" + (Math.abs(start - scrollTop)));
So, what is the best way to do it?
UPDATE:
Now i'm at this point, but i need to make it more smooth
jsFiddle
Try this
$(document).ready(function(){
var headerElement = //Select header element here,
scrollTopToLookoutFor = //Put value you want to check for here,
if($("body").scrollTop() > scrollTopToLookoutFor || $("html").scrollTop() > scrollTopToLookoutFor){
headerElement.addClass("fix-header");
}
else{
headerElement.removeClass("fix-header");
}
});
Have a css class here with required styles
.fix-header{
height: 400px;
position: fixed;
top: 0px;
}

How do you make a floating sidebar like envato?

I really like the floating panel on the left side of the following site:
http://envato.com/
I have no idea what its called, but I like how when you click on the search button, it expands to a search page, you click on another icon, and it expands with what appears like its own page.
How do I accomplish this? Is there some tutorial out there using html5, JavaScript or jQuery?
NOTE: All the answers so far only cover the floating bar, but not the clicking on a link on that floating bar to show a window expanded to the right.
<div id="float"></div>
#float{
position:fixed;
top:50px;
left:0;
}
Check working example at http://jsfiddle.net/TVwAv/
done using css,
HTML
<div id="floating_sidebar">
whatever you want to put here
</div>
CSS
#floating_sidebar {
position:fixed;
left: 0;
top: 100px; /* change to adjust height from the top of the page */
}
I am using this for a "floating (sticky) menu". What I have added is:
1. to avoid my 'footer' always being "scrolled" down in case the sidemenu is a little high, I only do the scrolling if necessary, i.e -
when the content is higher than the sidebar.
2. I found the animate effect a little "jumpy" to my taste, so I just changed the css through jquery. of-course you put a 0 in the animate time, but the animation still occurs, so it's cleaner and faster to use the css.
3. 100 is the height of my header. you can assume it to be the "threshold" of when to do the scrolling.
$(window).scroll(function(){
if ($('#sidebar').height() < $('#content').height())
{
if ($(this).scrollTop() > 90)
$('#sidebar').css({"margin-top": ($(this).scrollTop()) - 100 });
//$('#sidebar').animate({"marginTop": ($(this).scrollTop()) - 100 }, 0);
else
$('#sidebar').css({"margin-top": ($(this).scrollTop()) });
//$('#sidebar').animate({"marginTop": ($(this).scrollTop()) }, 0);
}
});`
you can use this ..
your html div is here
<div id="scrolling_div">Your text here</div>
And you javascript function is here
$(window).scroll(function(){
$('#scrolling_div').stop().animate({"marginTop": ($(this).scrollTop()) +10+ "px"}, "slow"});
});
You can also use the css for this
#scrolling_div {
position:absolute;
left: 0;
top: 100px;
}
I have not tested it but hopefully its worked.
I know this looks quite a big piece of code, however this function just works by specifying three simple options; your floater "top", your "target" (floater) and "reference" element to set the boundaries, it also takes care of the top and bottom position automatically, no css involved.
function scrollFloater(marginTop, reference, target, fixWhidth = false){
var processScroll = function(){
var from = reference.offset().top - marginTop;
var to = reference.offset().top + reference.outerHeight() + marginTop - target.outerHeight();
var scrollTop = $(this).scrollTop();
var bottom = to - reference.offset().top + marginTop;
if( fixWhidth )
target.css('width', target.width());
if( scrollTop > from && scrollTop < to )
target.css('position', 'fixed').css('top',marginTop);
else if( scrollTop >= to )
target.css('position', 'absolute').css('top', bottom);
else
target.css('position', '').css('top',marginTop);
}
$(window).scroll(function(){ processScroll(); });
processScroll();
}
And this is how you would use it:
$(function() {
scrollFloater(41, $('.box.auth.register'), $('.plans-floater'), true);
});
I hope this helps someone.

Categories

Resources