Keep left column visible AND scrollable - javascript

It's easy to keep a column in my layout fixed so it's always visible, even when the user scrolls down.
It's also easy to only move the column down the page when the page is scrolled down far enough for it to be out of the viewport so it's anchored before scrolling starts.
My problem is, I have left hand column that is taller than the average window so you need to be able to scroll down to see all the content (controls) in the left column but at the same time when you scroll up you want to see the top of the controls again.
Here's a visual of what I want to accomplish:
So the left column is always occupying 100% of the height of the window but as the user scrolls down they can see the bottom of the div, and when they start to scroll up the scrolls up until it reaches the top of the window again. So no matter how far they scroll the page, the top of the div is always nearby.
Is there some jQuery magic to make this happen?

Did you mean something like this? (Demo)
var sidebar = document.getElementById('sidebar');
var sidebarScroll = 0;
var lastScroll = 0;
var topMargin = sidebar.offsetTop;
sidebar.style.bottom = 'auto';
function update() {
var delta = window.scrollY - lastScroll;
sidebarScroll += delta;
lastScroll = window.scrollY;
if(sidebarScroll < 0) {
sidebarScroll = 0;
} else if(sidebarScroll > sidebar.scrollHeight - window.innerHeight + topMargin * 2) {
sidebarScroll = sidebar.scrollHeight - window.innerHeight + topMargin * 2;
}
sidebar.style.marginTop = -sidebarScroll + 'px';
}
document.addEventListener('scroll', update);
window.addEventListener('resize', update);
#sidebar {
background-color: #003;
bottom: 1em;
color: white;
left: 1%;
overflow: auto;
padding: 1em;
position: fixed;
right: 80%;
top: 1em;
}
body {
line-height: 1.6;
margin: 1em;
margin-left: 21%;
}
It almost degrades gracefully, too…

I made a fiddle for you, hope this helps you out abit.
I detect scroll up or scroll down, and set the fixed position accordion to the direction.
http://jsfiddle.net/8eruY/
CSS
aside {
position:fixed;
height:140%;
background-color:red;
width:100px;
top:20px;
left:20px;
}
Javascript
//Detect user scroll down or scroll up in jQuery
var mousewheelevt = (/Firefox/i.test(navigator.userAgent)) ? "DOMMouseScroll" : "mousewheel" //FF doesn't recognize mousewheel as of FF3.x
$('html').bind(mousewheelevt, function(e){
var evt = window.event || e //equalize event object
evt = evt.originalEvent ? evt.originalEvent : evt; //convert to originalEvent if possible
var delta = evt.detail ? evt.detail*(-40) : evt.wheelDelta //check for detail first, because it is used by Opera and FF
if(delta > 0) {
$('aside').css('top', '20px');
$('aside').css('bottom', 'auto');
}
else{
$('aside').css('bottom', '20px');
$('aside').css('top', 'auto');
}
});

http://jsfiddle.net/KCrFe/
or this:
.top-aligned {
position: fixed;
top: 10px;
}
with
var scrollPos
$(window).scroll(function(event){
var pos = $(this).scrollTop();
if ( pos < scrollPos){
$('.sidebar').addClass('top-aligned');
} else {
$('.sidebar').removeClass('top-aligned');
}
scrollPos = pos;
});

Related

Trying to get this smoother and more natural in behavior

My implementation,
http://kodhus.com/kodnest/land/PpNFTgp
I am curious, as I am not able for some reason to figure this out, how to get my JavaScript to make my slider behave more natural and smoother, if someone knows, how to, or can make this, feel free. I'd be happy to understand.
JavaScript:
const thumb = document.querySelector('.thumb');
const thumbIndicator = document.querySelector('.thumb .thumb-indicator');
const sliderContainer = document.querySelector('.slider-container');
const trackProgress = document.querySelector('.track-progress');
const sliderContainerStart = sliderContainer.offsetLeft;
const sliderContainerWidth = sliderContainer.offsetWidth;
var translate;
var dragging = false;
var percentage = 14;
document.addEventListener('mousedown', function(e) {
if (e.target.classList.contains('thumb-indicator')) {
dragging = true;
thumbIndicator.classList.add('focus');
}
});
document.addEventListener('mousemove', function(e) {
if (dragging) {
console.log('moving', e)
if (e.clientX < sliderContainerStart) {
translate = 0;
} else if (e.clientX > sliderContainerWidth + sliderContainerStart) {
translate = sliderContainerWidth;
} else {
translate = e.clientX - sliderContainer.offsetLeft;
}
thumb.style.transform = 'translate(-50%) translate(' + translate + 'px)';
trackProgress.style.transform = 'scaleX(' + translate / sliderContainerWidth + ')'
}
});
function setPercentage() {
thumb.style.transform = 'translate(-50%) translate(' + percentage/100 * sliderContainerWidth + 'px)';
trackProgress.style.transform = 'scaleX(' + percentage/100 + ')';
}
function init() {
setPercentage();
}
init();
document.addEventListener('mouseup', function(e) {
dragging = false;
thumbIndicator.classList.remove('focus');
});
EDIT: Is there a way to smoothly and naturally increment by one for every slow move?
Is it possible to make to behave as if, like when one clicks the progress bar so that it jumps there?
The kodhus site is very janky in my browser, so I can't tell if your code lacks responsiveness or whether it's the site itself. I feel that your code is a bit convoluted: translate and width / height are mixed unnecessarily; no need to use a dragging boolean when that information is always stored in the classlist. The following slider performs nicely, and has a few considerations I don't see in yours:
stopPropagation when clicking the .thumb element
drag stops if window loses focus
pointer-events: none; applied to every part of the slider but the .thumb element
let applySliderFeel = (slider, valueChangeCallback=()=>{}) => {
// Now `thumb`, `bar` and `slider` are the elements that concern us
let [ thumb, bar ] = [ '.thumb', '.bar' ].map(v => slider.querySelector(v));
let changed = amt => {
thumb.style.left = `${amt * 100}%`;
bar.style.width = `${amt * 100}%`;
valueChangeCallback(amt);
};
// Pressing down on `thumb` activates dragging
thumb.addEventListener('mousedown', evt => {
thumb.classList.add('active');
evt.preventDefault();
evt.stopPropagation();
});
// Releasing the mouse button (anywhere) deactivates dragging
document.addEventListener('mouseup', evt => thumb.classList.remove('active'));
// If the window loses focus dragging also stops - this can be a very
// nice quality of life improvement!
window.addEventListener('blur', evt => thumb.classList.remove('active'));
// Now we have to act when the mouse moves...
document.addEventListener('mousemove', evt => {
// If the drag isn't active do nothing!
if (!thumb.classList.contains('active')) return;
// Compute `xRelSlider`, which is the mouse position relative to the
// left side of the slider bar. Note that *client*X is compatible with
// getBounding*Client*Rect, and using these two values we can quickly
// get the relative x position.
let { width, left } = slider.getBoundingClientRect();
// Consider mouse x, subtract left offset of slider, and subtract half
// the width of the thumb (so drags position the center of the thumb,
// not its left side):
let xRelSlider = evt.clientX - left - (thumb.getBoundingClientRect().width >> 1);
// Clamp `xRelSlider` between 0 and the slider's width
if (xRelSlider < 0) xRelSlider = 0;
if (xRelSlider > width) xRelSlider = width;
// Apply styling (using percents is more robust!)
changed(xRelSlider / width);
evt.preventDefault();
evt.stopPropagation();
});
slider.addEventListener('mousedown', evt => {
let { width, left } = slider.getBoundingClientRect();
// Clicking the slider also activates a drag
thumb.classList.add('active');
// Consider mouse x, subtract left offset of slider, and subtract half
// the width of the thumb (so drags position the center of the thumb,
// not its left side):
let xRelSlider = evt.clientX - left - (thumb.getBoundingClientRect().width >> 1);
// Apply styling (using percents is more robust!)
changed(xRelSlider / width);
evt.preventDefault();
evt.stopPropagation();
});
changed(0);
};
let valElem = document.querySelector('.value');
applySliderFeel(document.querySelector('.slider'), amt => valElem.innerHTML = amt.toFixed(3));
.slider {
position: absolute;
width: 80%; height: 4px; background-color: rgba(0, 0, 0, 0.3);
left: 10%; top: 50%; margin-top: -2px;
}
.slider > .bar {
position: absolute;
left: 0; top: 0; width: 0; height: 100%;
background-color: #000;
pointer-events: none;
}
.slider > .thumb {
position: absolute;
width: 20px; height: 20px; background-color: #000; border-radius: 100%;
left: 0; top: 50%; margin-top: -10px;
}
.slider > .thumb.active {
box-shadow: 0 0 0 5px rgba(0, 0, 0, 0.5);
}
<div class="slider">
<div class="bar"></div>
<div class="thumb"></div>
</div>
<div class="value"></div>

Animate div when the scrollbar reaches certain position

My website at the moment has three sections in a single scroll layout. With a Heading for two sections: About & Contact (these are div boxes) that animate when you scroll to the bottom of the page. What I'm trying to achieve is having the animation take place when the user scrolls down and hits the bottom of each (div box) section as opposed to the bottom of the website.
I believe I need to implement the .offset() function but unsure if that is correct?
Any help would be greatly appreciated.
CSS
.header {
display: none;
position: relative;
left: 0px;
right: 0px;
top: 500px;
height: 80px;
width: 100%;
background:red;
color: #fff;
text-align: center;
}
JS
var header = $('.header'),
extra = 10; // In case you want to trigger it a bit sooner than exactly at the bottom.
header.css({ opacity: '0', display: 'block' });
$(window).scroll(function() {
var scrolledLength = ( $(window).height() +extra) + $(window).scrollTop(),
documentHeight = $(document).height();
console.log( 'Scroll length: ' + scrolledLength + ' Document height: ' + documentHeight )
if( scrolledLength >= documentHeight ) {
header
.addClass('top')
.stop().animate({ top: '20', opacity: '1' }, 800);
}
else if ( scrolledLength <= documentHeight && header.hasClass('top') ) {
header
.removeClass('top')
.stop().animate({ top: '500', opacity: '0' }, 800);
}
});
Fiddle - http://jsfiddle.net/SFPpf/480/
Looks like position() would be better in this case. The position method is relative to the document whereas offset is relative to the parent element. It returns an object with the properties "top" and "left". It can only return the position of one element at a time, so for the first div, you would need to use first() and eq() to get a specific one.
The bottom of a .fillWindow will be its vertical position + its height.
var $fillWindow = $(".fillWindow").first(), // or eq() for others
position = $fillWindow.position(),
height = $fillWindow.height();
//bottom = position.top + height;
scrollTop() can now be used to check when the user scrolls past the .fillWindow.
if ( $(window).scrollTop() >= position.top ) {
// do the animation here
} else {
// do something else
}
Edit: I just caught my mistake. It should be $(window).scrollTop(). You should also just test for scrollTop being at the top of the .fillWindow.

y position issue for background images via css and javascript

I have implemented a parallax scrolling effect based on a tutorial I found. The effect works great. However, when I specify the background images, I am unable to control the y (vertical) axis. This is causing problems because I'm trying to set locations on multiple layered images.
Any thoughts on what's causing the problem?
Here is one external script:
$(document).ready(function(){
$('#nav').localScroll(800);
//.parallax(xPosition, speedFactor, outerHeight) options:
//xPosition - Horizontal position of the element
//inertia - speed to move relative to vertical scroll. Example: 0.1 is one tenth the speed of scrolling, 2 is twice the speed of scrolling
//outerHeight (true/false) - Whether or not jQuery should use it's outerHeight option to determine when a section is in the viewport
$('#mainimagewrapper').parallax("50%", 1.3);
$('#secondaryimagewrapper').parallax("50%", 0.5);
$('.image2').parallax("50%", -0.1);
$('#aboutwrapper').parallax("50%", 1.7);
$('.image4').parallax("50%", 1.5);
})
This is another external script:
(function( $ ){
var $window = $(window);
var windowHeight = $window.height();
$window.resize(function () {
windowHeight = $window.height();
});
$.fn.parallax = function(xpos, speedFactor, outerHeight) {
var $this = $(this);
var getHeight;
var firstTop;
var paddingTop = 0;
//get the starting position of each element to have parallax applied to it
$this.each(function(){
firstTop = $this.offset().top;
});
if (outerHeight) {
getHeight = function(jqo) {
return jqo.outerHeight(true);
};
} else {
getHeight = function(jqo) {
return jqo.height();
};
}
// setup defaults if arguments aren't specified
if (arguments.length < 1 || xpos === null) xpos = "50%";
if (arguments.length < 2 || speedFactor === null) speedFactor = 0.1;
if (arguments.length < 3 || outerHeight === null) outerHeight = true;
// function to be called whenever the window is scrolled or resized
function update(){
var pos = $window.scrollTop();
$this.each(function(){
var $element = $(this);
var top = $element.offset().top;
var height = getHeight($element);
// Check if totally above or totally below viewport
if (top + height < pos || top > pos + windowHeight) {
return;
}
$this.css('backgroundPosition', xpos + " " + Math.round((firstTop - pos) * speedFactor) + "px");
});
}
$window.bind('scroll', update).resize(update);
update();
};
})(jQuery);
Here is the CSS for one section:
#aboutwrapper {
background-image: url(../images/polaroid.png);
background-position: 50% 0;
background-repeat: no-repeat;
background-attachment: fixed;
color: white;
height: 500px;
width: 100%;
margin: 0 auto;
padding: 0;
}
#aboutwrapper .image4 {
background: url(../images/polaroid2.png) 50% 0 no-repeat fixed;
height: 500px;
width: 100%;
margin: 0 auto;
padding: 0;
}
.image3{
margin: 0 auto;
min-width: 970px;
overflow: auto;
width: 970px;
}
Both of these are being called to achieve the parallax scrolling. I really just want to more specifically control the background image locations. I've tried messing with the CSS background position and I've messed with the first javascript snippet as well. No luck.
just a quick shot, have you tried actually placing the images, either in a div or just using the img src tag to actually move the element rather than manipulating the y axis of a background image?

Sticky Footer and Animation

I found this jsfiddle here at stackoverflow, but the solution provided by the person is very jumpy. http://jsfiddle.net/BramVanroy/ZVzEe/ I need something very smooth.
var secondary = $("#secondary-footer");
secondary.hide().addClass("fixed").fadeIn("fast");
$(window).scroll(function() {
if (secondary.offset().top >= ($(document).height() - 350)) {
secondary.removeClass("fixed");
}
else if(secondary + ":not('.fixed')") {
secondary.addClass("fixed");
}
});
How I need the sticky footer to work is for it to show the footer as a narrow bar at the bottom of the page while still scrolling through the content. Once the bottom of the page is reached with the scrollbar, the footer will expand in height.
The jsfiddle provided is very close to how I need this to work, but I need something very smooth. And another note, the height of the fully expanded footer is not fixed. Thanks to everyone for your help.
demo
jQuery
var secondary = $("#secondary-footer");
secondary.hide().addClass("fixed").fadeIn("fast");
$(window).scroll(function() {
var scrollBottom = $(window).scrollTop() + $(window).height();
$("#content").css("bottom",secondary.height());
var maxHeight = 350; // set maximum height of the footer here
var minHeight = 120; // set the minimum height of the footer here
secondary.height(maxHeight - ($(document).height() - scrollBottom));
if (secondary.height() <= minHeight) secondary.height(minHeight);
});
CSS
#content {
width: 90%;
margin: 0 auto;
padding: 0.5em;
background: #dedede;
position:relative; /* added this */
}
#secondary-footer {
width: 100%;
height: 120px;
background: #666;
position: fixed;
bottom: 0;
left: 0;
}
/* removed #secondary-footer.fixed and merged content with #secondary-footer */
Another solution: http://jsfiddle.net/27rNu/
jQuery
$(document).ready(function() {
var secondary = $("#secondary-footer");
secondary.addClass("fixed");
var windowH = $('#wrapper').outerHeight(true);
$(window).scroll(function() {
var scrollVal = $(this).scrollTop();
if (scrollVal < (windowH - 350 * 2)) {
secondary.addClass("fixed");
}
else {
secondary.removeClass("fixed");
}
});
});
I also added a "wrapper" div around the whole html.

JavaScript get window X/Y position for scroll

I'm hoping to find a way to get the current viewable window's position (relative to the total page width/height) so I can use it to force a scroll from one section to another. However, there seems to be a tremendous amount of options when it comes to guessing which object holds the true X/Y for your browser.
Which of these do I need to make sure IE 6+, FF 2+, and Chrome/Safari work?
window.innerWidth
window.innerHeight
window.pageXOffset
window.pageYOffset
document.documentElement.clientWidth
document.documentElement.clientHeight
document.documentElement.scrollLeft
document.documentElement.scrollTop
document.body.clientWidth
document.body.clientHeight
document.body.scrollLeft
document.body.scrollTop
And are there any others? Once I know where the window is I can set an event chain that will slowly call window.scrollBy(x,y); until it reaches my desired point.
The method jQuery (v1.10) uses to find this is:
var doc = document.documentElement;
var left = (window.pageXOffset || doc.scrollLeft) - (doc.clientLeft || 0);
var top = (window.pageYOffset || doc.scrollTop) - (doc.clientTop || 0);
That is:
It tests for window.pageXOffset first and uses that if it exists.
Otherwise, it uses document.documentElement.scrollLeft.
It then subtracts document.documentElement.clientLeft if it exists.
The subtraction of document.documentElement.clientLeft / Top only appears to be required to correct for situations where you have applied a border (not padding or margin, but actual border) to the root element, and at that, possibly only in certain browsers.
Maybe more simple;
var top = window.pageYOffset || document.documentElement.scrollTop,
left = window.pageXOffset || document.documentElement.scrollLeft;
Credits: so.dom.js#L492
Using pure javascript you can use Window.scrollX and Window.scrollY
window.addEventListener("scroll", function(event) {
var top = this.scrollY,
left =this.scrollX;
}, false);
Notes
The pageXOffset property is an alias for the scrollX property, and The
pageYOffset property is an alias for the scrollY property:
window.pageXOffset == window.scrollX; // always true
window.pageYOffset == window.scrollY; // always true
Here is a quick demo
window.addEventListener("scroll", function(event) {
var top = this.scrollY,
left = this.scrollX;
var horizontalScroll = document.querySelector(".horizontalScroll"),
verticalScroll = document.querySelector(".verticalScroll");
horizontalScroll.innerHTML = "Scroll X: " + left + "px";
verticalScroll.innerHTML = "Scroll Y: " + top + "px";
}, false);
*{box-sizing: border-box}
:root{height: 200vh;width: 200vw}
.wrapper{
position: fixed;
top:20px;
left:0px;
width:320px;
background: black;
color: green;
height: 64px;
}
.wrapper div{
display: inline;
width: 50%;
float: left;
text-align: center;
line-height: 64px
}
.horizontalScroll{color: orange}
<div class=wrapper>
<div class=horizontalScroll>Scroll (x,y) to </div>
<div class=verticalScroll>see me in action</div>
</div>
Maybe this has not been mentioned due to this article been 11 years old.
But currently I am using window.scrollY (inside an onscroll event listner and a throttle function) and it works just fine most of the time.
And when it doesn't I use intersectionObserver API for similar effect which is also a fairly new feature I guess.
if (window.scrollY > desiredAmount) {
doThis();
}
function FastScrollUp()
{
window.scroll(0,0)
};
function FastScrollDown()
{
$i = document.documentElement.scrollHeight ;
window.scroll(0,$i)
};
var step = 20;
var h,t;
var y = 0;
function SmoothScrollUp()
{
h = document.documentElement.scrollHeight;
y += step;
window.scrollBy(0, -step)
if(y >= h )
{clearTimeout(t); y = 0; return;}
t = setTimeout(function(){SmoothScrollUp()},20);
};
function SmoothScrollDown()
{
h = document.documentElement.scrollHeight;
y += step;
window.scrollBy(0, step)
if(y >= h )
{clearTimeout(t); y = 0; return;}
t = setTimeout(function(){SmoothScrollDown()},20);
}

Categories

Resources