Div element walk with scrolling, smooth - javascript

I have just started a new website. It's important for me that the users sees this container, so I want it to scroll with the site.
I have an example for this thing: http://gruen-weiss-mannheim.de/
On this site on the left its a green container who stays with smooth scroll on the site if someone scrolls.
I hope you can help me, because I have already tried something, but in this way the container is always on the top.
Would be great If you could help me find a solution!
try {
window.onscroll = setNavPosition;
}
catch(e) {
document.documentElement.onscroll = setNavPosition;
}
function setNavPosition(){
$('.smooth').stop();
try {
if (document.body.scrollTop > document.documentElement.scrollTop) {
var targetPosition = document.body.scrollTop;
}
else {
var targetPosition = document.documentElement.scrollTop;
}
}
catch(e) {
var targetPosition = document.documentElement.scrollTop;
}
$('.smooth').animate({top: targetPosition}, 600);
}
.smooth {
height: 40px;
background-color: orange;
z-index: 2;
position: absolute;
width: 50px;
top: 50px;
}
.body {
height: 700px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="body"></div>
<div class="smooth"></div>
So every time I scroll, the container gets back to the top, not with the space in between...

If what you mean is that after the first scrolling it always stops by the edge of the viewport, it is because of this lines var targetPosition = document.body.scrollTop; and var targetPosition = document.documentElement.scrollTop;. I changed them:
try {
window.onscroll = setNavPosition;
}
catch(e) {
document.documentElement.onscroll = setNavPosition;
}
function setNavPosition(){
$('.smooth').stop();
try {
if (document.body.scrollTop > document.documentElement.scrollTop) {
var targetPosition = document.body.scrollTop + 50;
}
else {
var targetPosition = document.documentElement.scrollTop + 50;
}
}
catch(e) {
var targetPosition = document.documentElement.scrollTop;
}
$('.smooth').animate({top: targetPosition}, 600);
}
.smooth {
height: 40px;
background-color: orange;
z-index: 2;
position: absolute;
width: 50px;
top: 50px;
}
.body {
height: 700px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="body"></div>
<div class="smooth"></div>

Related

Disable running javascript when scrolling from computer and phone

This script automatically scrolls to the bottom of the page
1- How do I scroll to a specific {Div} in the middle of the page only and auto scroll gets disabled
2- If the user scrolls down from the computer or phone manually, the automatic descent will be disabled
function scrollpage() {
function f()
{
window.scrollTo(0,i);
if(status==0) {
i=i+0.1;
if(i>=Height){ status=1; }
} else {
}
setTimeout( f, 0.5 );
}f();
}
var Height=document.documentElement.scrollHeight;
var i=1,j=Height,status=0;
scrollpage();
<div style=" background: #f00; width: 100%; height: 100vh; "></div>
<div style=" background: #000; width: 100%; height: 100vh; "></div>
<div style=" background: #2700ff; width: 100%; height: 100vh; "></div>
You can add an event listener to do another action when the user emits a scroll event
I did a little bit of other stuff to make it scroll slowly when a user isn't scrolling and then stop when a user is scrolling
I only tested it on my laptop so far, feel free to test it out on other devices
function scrollpage() {
function f()
{
if(STATUS===0) {
expectedPos=window.scrollY+1
window.scrollTo(0,expectedPos);
}
}
setInterval(f,80) //calls f every 80ms
}
var STATUS=0; //status is already a global variable on some browsers
var expectedPos=null; //will be expected position of the interval's scroll.. any other scroll is from human most likely
scrollpage();
let timeout=null; //will be a timeout for waiting for scroll INACTIVITY
function inactive(){ STATUS=0; }
window.addEventListener('scroll',function(e){
if(expectedPos!==window.scrollY){ STATUS=1; }
clearTimeout(timeout);
timeout=setTimeout(inactive,5000)
})
<div style=" background: #f00; width: 100%; height: 100vh; "></div>
<div style=" background: #000; width: 100%; height: 100vh; "></div>
<div style=" background: #2700ff; width: 100%; height: 100vh; "></div>
With this you can customize the scrolling speed and choose the element to which you want to scroll to; any mousewheel event will automatically disable the autoscrolling.
let isAutoscrolling = false;
let isScrolling = false;
let scrollPage;
function autoScroll(scroll) {
window.scrollTo(0, scroll.amount);
if (scroll.target === window) {
if ((window.innerHeight + window.scrollY) >= document.body.offsetHeight) {
disableAutoScroll();
}
}
if (scroll.target.tagName) {
if (window.scrollY >= scroll.target.offsetTop) {
disableAutoScroll();
}
} else {
throw ("invalid scroll target")
disableAutoScroll();
}
scroll.amount += scroll.speed;
}
function enableAutoScroll() {
if (isScrolling) return;
isAutoscrolling = true;
scrollPage = setInterval(autoScroll, 16, {
amount: 0,
speed: 0.5,
target: document.getElementById("scrollTarget")
});
}
function disableAutoScroll() {
if (!isScrolling) isScrolling = true;
if (isAutoscrolling) {
isAutoscrolling = false;
clearInterval(scrollPage)
}
}
function initializeAutoScroll() {
//Autoscroll immediately
//enableAutoScroll();
//Autoscroll after 1 second
setTimeout(enableAutoScroll, 1000);
//Autoscroll after loading the page content
//window.addEventListener("DOMContentLoaded", enableAutoScroll);
document.body.addEventListener('wheel', disableAutoScroll);
document.body.addEventListener('touchmove', disableAutoScroll);
}
initializeAutoScroll();
<div style="background: #f00; width: 100%; height: 100vh;"></div>
<div id="scrollTarget" style="background: #000; width: 100%; height: 100vh;"></div>
<div style="background: #2700ff; width: 100%; height: 100vh;"></div>
I created a second version of the autoscrolling function that can be called directly without any initializer, I think its more flexible than the first version
let autoscrollAnimation;
let isAutoscrolling = false;
let isScrolling = false;
function animateAutoScroll(scroll) {
window.scrollTo(0, scroll.amount);
if (scroll.target === window) {
if ((window.innerHeight + window.scrollY) >= document.body.offsetHeight) {
disableAutoScroll();
return;
}
} else if (scroll.target.tagName) {
if (scroll.speed > 0 && window.scrollY >= scroll.target.offsetTop) {
disableAutoScroll();
return;
}
if (scroll.speed < 0 && window.scrollY <= scroll.target.offsetTop) {
disableAutoScroll();
return;
}
} else {
disableAutoScroll();
throw ("invalid scroll target");
return;
}
scroll.amount += scroll.speed;
}
function disableAutoScroll() {
if (!isScrolling) isScrolling = true;
if (isAutoscrolling) {
isAutoscrolling = false;
clearInterval(autoscrollAnimation)
}
}
function AutoScroll(from_position = 0, to_element = window, scroll_speed = 0.5, scroll_delay = 0) {
document.body.addEventListener('wheel', disableAutoScroll);
document.body.addEventListener('touchmove', disableAutoScroll);
from_position = Math.max(0, Math.min(from_position, document.body.offsetHeight - window.innerHeight))
isAutoscrolling = false;
isScrolling = false;
if (to_element.tagName && from_position > to_element.offsetTop) {
scroll_speed *= -1;
}
setTimeout(function() {
if (isScrolling) return;
isAutoscrolling = true;
autoscrollAnimation = setInterval(animateAutoScroll, 16, {
amount: from_position,
speed: scroll_speed,
target: to_element
});
}, scroll_delay);
}
AutoScroll(
0, /*Starting position of autoscrolling*/
document.getElementById("scrollTarget"), /*Ending position of autoscrolling */
1, /*Autoscrolling speed*/
1000 /*Autoscrolling delay*/
)
<div style="background: #f00; width: 100%; height: 100vh;"></div>
<div id="scrollTarget" style="background: #000; width: 100%; height: 100vh;"></div>
<div style="background: #2700ff; width: 100%; height: 100vh;"></div>

Stop fixed element scrolling at certain point

I have fixed sidebar which should scroll along with main content and stop at certain point when I scroll down. And vise versa when I scroll up.
I wrote script which determines window height, scrollY position, position where sidebar should 'stop'. I stop sidebar by adding css 'bottom' property. But I have 2 problems with this approach:
When sidebar is close to 'pagination' where it should stop, it suddenly jumps down. When I scroll up it suddenly jumps up.
When I scroll page, sidebar moves all the time
Here's my code. HTML:
<div class="container">
<aside></aside>
<div class="content">
<div class="pagination"></div>
</div>
<footer></footer>
</div>
CSS:
aside {
display: flex;
position: fixed;
background-color: #fff;
border-radius: 4px;
transition: 0s;
transition: margin .2s, bottom .05s;
background: orange;
height: 350px;
width: 200px;
}
.content {
display: flex;
align-items: flex-end;
height: 1000px;
width: 100%;
background: green;
}
.pagination {
height: 100px;
width: 100%;
background: blue;
}
footer {
height: 500px;
width: 100%;
background: red;
}
JS:
let board = $('.pagination')[0].offsetTop;
let filterPanel = $('aside');
if (board <= window.innerHeight) {
filterPanel.css('position', 'static');
filterPanel.css('padding-right', '0');
}
$(document).on('scroll', function () {
let filterPanelBottom = filterPanel.offset().top + filterPanel.outerHeight(true);
let bottomDiff = board - filterPanelBottom;
if(filterPanel.css('position') != 'static') {
if (window.scrollY + window.innerHeight - (bottomDiff*2.6) >= board)
filterPanel.css('bottom', window.scrollY + window.innerHeight - board);
else
filterPanel.css('bottom', '');
}
});
Here's live demo on codepen
Side bar is marked with orange background and block where it should stop is marked with blue. Than you for your help in advance.
I solved my problem with solution described here
var windw = this;
let board = $('.pagination').offset().top;
let asideHeight = $('aside').outerHeight(true);
let coords = board - asideHeight;
console.log(coords)
$.fn.followTo = function ( pos ) {
var $this = this,
$window = $(windw);
$window.scroll(function(e){
if ($window.scrollTop() > pos) {
$this.css({
position: 'absolute',
top: pos
});
} else {
$this.css({
position: 'fixed',
top: 0
});
}
});
};
$('aside').followTo(coords);
And calculated coordinates as endpoint offset top - sidebar height. You can see solution in my codepen

how to make a box reach the edge of a bigger box

javascript beginner here! so i'm trying to do a box(that is inside a larger box) move from the top to the edge of the box. Here's the code:
var boxcont = document.getElementById("boxcont");
var boxbtn = document.getElementById("boxbtn");
boxbtn.addEventListener("click", function() {
var loc = 0;
var timebox = setInterval(boxmove, 5);
function boxmove() {
if (loc == 320) {
clearInterval(timebox);
} else {
loc++;
boxcont.style.top = loc + "px";
boxcont.style.left = loc + "px";
}
}
});
#movebox {
width: 300px;
height: 350px;
background-color: grey;
}
#boxcont {
width: 30px;
height: 30px;
background-color: indianred;
position: relative;
}
<div id="movebox">
<div id="boxcont"></div>
</div>
<button id="boxbtn">Move the box</button>
The problem is that the small box doesn't exactly ends up at the edge, it goes more to the right. I tried doing
boxcont.style.left = (loc - 0.5) + "px";
but doesn't work. pretty sure the solution is simple but as a newbie here it's confusing me :p. Oh and i also tried doing ++ to the 0.5 and Number(0.5) so it reads it as a decimal but still doesn't work!
the big gray box is not set to the correct height and width that corresponds with the small red box's movement. You have it going down 1 and to the right 1 every 5 however, your actually going across a rectangle, not a square. set your width and height the same for the gray box and slightly adjust the stopping point to a little bit less.
var boxcont = document.getElementById("boxcont");
var boxbtn = document.getElementById("boxbtn");
boxbtn.addEventListener("click", function() {
var loc = 0;
var timebox = setInterval(boxmove, 5); // every five milliseconds
function boxmove() {
if (loc == 290) {
clearInterval(timebox);
} else {
loc++;
boxcont.style.top = loc + "px";
boxcont.style.left = loc + "px";
}
}
});
#movebox {
width: 300px;
height: 350px;
background-color: grey;
}
#boxcont {
width: 30px;
height: 30px;
background-color: indianred;
position: relative;
}
<div id="movebox" style = "height: 320px; width: 320px">
<div id="boxcont" ></div>
</div>
<button id="boxbtn">Move the box</button>
if (loc == 270) {
instead of
if (loc == 320) {
Gets you there.
300px is the width of the containing div and the moving div is 30px wide so 300-30=270px
var boxcont = document.getElementById("boxcont");
var boxbtn = document.getElementById("boxbtn");
boxbtn.addEventListener("click", function() {
var loc = 0;
var timebox = setInterval(boxmove, 5);
function boxmove() {
if (loc == 270) {
clearInterval(timebox);
} else {
loc++;
boxcont.style.top = loc + "px";
boxcont.style.left = loc + "px";
}
}
});
#movebox {
width: 300px;
height: 350px;
background-color: grey;
}
#boxcont {
width: 30px;
height: 30px;
background-color: indianred;
position: relative;
}
<div id="movebox">
<div id="boxcont"></div>
</div>
<button id="boxbtn">Move the box</button>

Horizontal scroll at the middle of the page

I want to change the scroll direction at the middle of the page.
I tried to do it with "jInvertScroll", but this plugin increase left in css, like that:left: /* increase on scroll */ px ;
So if I want to change the scroll direction to the middle of the page, left will already have a value like:left: -1500px;
That's my problem.
Is there another way to do it?
HTML :
<div class="vertical"></div>
<div class="menu-change"></div>
<div class="horizontal">
<p>scroll</p>
</div>
CSS :
body {
overflow-x: hidden;
padding: 0;
margin: 0;
}
.scroll {
position: fixed;
bottom: 0;
left: 0;
}
.vertical {
width: 100vw;
height: 2500px;
background-image: url(https://source.unsplash.com/random);
}
.horizontal {
width: 8500px;
height: 100vh;
background-image: url(https://source.unsplash.com/random);
}
JS :
$(document).ready(function(){
var scroll_start = 0;
var startchange = $('.menu-change');
var offset = startchange.offset();
$(document).scroll(function() {
scroll_start = $(this).scrollTop();
if(scroll_start > offset.top) {
$('.horizontal').addClass('scroll');
var elem = $.jInvertScroll(['.scroll'],
{
onScroll: function(percent) {
console.log(percent);
}
});
$(window).resize(function() {
if ($(window).width() <= 0) {
elem.destroy();
}
else {
elem.reinitialize();
}
});
} else {
$('.horizontal').removeClass('scroll');
}
});
});

Changing opacity when scrolling

My goal is to change the opacity of a DIV when I scroll down. It's important that the transition is smooth!
When the scrollTop of the body is 400, the opacity of the Test-div should be 1.
When the scrollTop of the body is 800, the opacity of the Test-div should be 0.
This is what I currently have, but it doesn't work.
window.addEventListener('scroll', function() {
if (document.body.scrollTop > 400) {
var currScrollPos2 = document.body.scrollTop;
document.getElementById('test').style.opacity = -currScrollPos2 / 400 + 2;
}
}
};
* {
margin: 0;
padding: 0;
}
body {
height: 2000px;
width: 100%;
}
#test {
width: 200px;
height: 200px;
background-color: red;
position: fixed;
}
<div id="test"></div>
You are close, but the body.scrollTop property does not work in all browsers.
I took the liberty of cleaning up your markup and code a little bit. You were missing a closing parenthesis at the end of you JavaScript, for example. There were also some superfluous rules in your CSS markup, that I deleted.
var test = document.getElementById('test');
window.addEventListener('scroll', function(e) {
// http://stackoverflow.com/a/28633515/962603
var scroll = window.pageYOffset || document.documentElement.scrollTop ||
document.body.scrollTop || 0;
test.style.opacity = Math.max(0, Math.min(1, -scroll / 400 + 2));
});
* {
margin: 0;
padding: 0;
}
body {
height: 2000px;
}
#test {
position: fixed;
width: 200px;
height: 200px;
background-color: red;
}
<div id="test"></div>
I had to replace document.body.scrollTop with window.pageYOffset to make it work.
See: document.body.scrollTop Firefox returns 0.
window.addEventListener('scroll', function() {
var currScrollPos2 = window.pageYOffset || document.documentElement.scrollTop || document.body.scrollTop || 0;
if (currScrollPos2 > 400) {
document.getElementById('test').style.opacity = -currScrollPos2 / 400 + 2;
}
}
);
* {
margin: 0;
padding: 0;
}
body {
height: 2000px;
width: 100%;
}
#test {
width: 200px;
height: 200px;
background-color: red;
position: fixed;
}
<div id="test"></div>
Just syntax error. Replace '}' by ')' at the end of your JS code.
Btw, I recommend using document.addEventListener instead of window.addEventListener
Here is correct code: https://jsfiddle.net/ye082ae9/
document.addEventListener('scroll', function(e) {
if (document.body.scrollTop > 400) {
var currScrollPos2 = document.body.scrollTop;
document.getElementById('test').style.opacity = -currScrollPos2/400 + 2;
}
});
Your code works fine, there is one little spelling error at the end. Just change }; to );
window.addEventListener('scroll', function() {
if (document.body.scrollTop > 400) {
var currScrollPos2 = document.body.scrollTop;
document.getElementById('test').style.opacity = -currScrollPos2/400 + 2;
}
}
);

Categories

Resources