Treating each div as a "page" when scrolling - javascript

I have a page that I'm building and I would like to make it that when I scroll (up or down) the page scrolls to the next div (each div is 100% the height of the window). And gets "fixed" there until you scroll again. An example of what I'm trying to accomplish can be seen here:
http://testdays.hondamoto.ch/
You will notice that when you scroll down, it automatically moves you to the next "div".
What I've tried:
Using the jQuery .scroll event combined with:
function updatePosition() {
if(canScroll) {
var pageName;
canScroll = false;
var st = $(window).scrollTop();
if (st > lastScrollTop){
// downscroll code
if(pageNumber < 7) {
pageNumber++;
}
pageName = '#' + getPageToScrollTo().id;
$('body').animate({ scrollTop: $(pageName).offset().top }, 2000, function() {
canScroll = true;
});
} else {
// upscroll code
if(pageNumber > 0) {
pageNumber--;
}
pageName = '#' + getPageToScrollTo().id;
$('body').animate({ scrollTop: $(pageName).offset().top }, 2000, function() {
canScroll = true;
});
}
lastScrollTop = st;
}
}
But the scroll event was getting called when the page was scrolling (animating), AND when the user scrolled. I only need it to be called when the user scrolls.
Then I added:
var throttled = _.throttle(updatePosition, 3000);
$(document).scroll(throttled);
From the Underscore.js library - but it still did the same.
Finally, I browsed here a bit and found:
Call Scroll only when user scrolls, not when animate()
But I was unable to implement that solution. Is there anyone that knows of any libraries or methods to get this working?
EDIT:
Solution based on Basic's answer:
function nextPage() {
canScroll = false;
if(pageNumber < 7) {
pageNumber++;
}
pageName = getPageToScrollTo();
$('html, body').stop().animate({ scrollTop: $(pageName).offset().top }, 1000, function() {
canScroll = true;
});
}
function prevPage() {
canScroll = false;
if(pageNumber > 0) {
pageNumber--;
}
pageName = getPageToScrollTo();
$('html, body').stop().animate({ scrollTop: $(pageName).offset().top }, 1000, function() {
canScroll = true;
});
}
//--Bind mouseWheel
$(window).on(mousewheelevt, function(event) {
event.preventDefault();
if(canScroll){
if(mousewheelevt == "mousewheel") {
if (event.originalEvent.wheelDelta >= 0) {
prevPage();
} else {
nextPage();
}
} else if(mousewheelevt == "DOMMouseScroll") {
if (event.originalEvent.detail >= 0) {
nextPage();
} else {
prevPage();
}
}
}
});

Ok...
The relevant code for the Honda site can be found in http://testdays.hondamoto.ch/js/script_2.js. It seems to be doing some calculations to locate the top of the div then scroll to it. There are handlers for different types of scrolling.
Specifically, the movement is handled by function navigation(target)
the key bits is here...
$('html,body').stop().animate({
scrollTop: $(target).offset().top + newMargin
}, 1000,'easeInOutExpo',function(){
//Lots of "page"-specific stuff
}
});
There are handlers for the scroll types...
$('body').bind('touchstart', function(event) {
//if(currentNav!=3){
// jQuery clones events, but only with a limited number of properties for perf reasons. Need the original event to get 'touches'
var e = event.originalEvent;
scrollStartPos = e.touches[0].pageY;
//}
});
//--Bind mouseWheel
$('*').bind('mousewheel', function(event, delta) {
event.preventDefault();
//trace('class : '+$(this).attr('class') + ' id : '+$(this).attr('id'));
if(!busy && !lockScrollModel && !lockScrollMap){
if(delta<0){
nextPage();
}else{
prevPage();
}
}
});
You'll note that the navigate() function sets a busy flag which is unset when scrolling completes - which is how it suppresses all new scroll events during a scroll. Try changing the direction of scroll while the page is already scrolling and you'll notice user input is being ignored too.

Related

How to change this script to autoscroll?

I have a script which has a button to scroll the site but I need it to scroll automatically on page load. I need the script to scroll exactly like shown below, except the button. Could anyone change it for me? I'm new to javascript, thanks..
function scroll(element, speed) {
var distance = element.height();
var duration = distance / speed;
element.animate({scrollTop: distance}, duration, 'linear');
}
$(document).ready(function() {
$("button").click(function() {
scroll($("html, body"), 0.015); // Set as required
});
});
Call the scroll function in on window load, this will scroll the page on load finished.
$(window).on('load', function(){
scroll($("html, body"), 0.015); // Set as required
})
You can try the below JavaScript code
var div = $('.autoscroller');
$('.autoscroller').bind('scroll mousedown wheel DOMMouseScroll mousewheel keyup', function(evt) {
if (evt.type === 'DOMMouseScroll' || evt.type === 'keyup' || evt.type === 'mousewheel') {
}
if (evt.originalEvent.detail < 0 || (evt.originalEvent.wheelDelta && evt.originalEvent.wheelDelta > 0)) {
clearInterval(autoscroller);
}
if (evt.originalEvent.detail > 0 || (evt.originalEvent.wheelDelta && evt.originalEvent.wheelDelta < 0)) {
clearInterval(autoscroller);
}
});
var autoscroller = setInterval(function(){
var pos = div.scrollTop();
if ((div.scrollTop() + div.innerHeight()) >= div[0].scrollHeight) {
clearInterval(autoscroller);
}
div.scrollTop(pos + 1);
}, 50);
here on the load of the page. The text are auto-scrolled upto the end of the page.

Detecting scroll direction

So I am trying to use the JavaScript on scroll to call a function. But I wanted to know if I could detect the direction of the the scroll without using jQuery. If not then are there any workarounds?
I was thinking of just putting a 'to top' button but would like to avoid that if I could.
I have now just tried using this code but it didn't work:
if document.body.scrollTop <= 0 {
alert ("scrolling down")
} else {
alert ("scrolling up")
}
It can be detected by storing the previous scrollTop value and comparing the current scrollTop value with it.
JavaScript :
var lastScrollTop = 0;
// element should be replaced with the actual target element on which you have applied scroll, use window in case of no target element.
element.addEventListener("scroll", function(){ // or window.addEventListener("scroll"....
var st = window.pageYOffset || document.documentElement.scrollTop; // Credits: "https://github.com/qeremy/so/blob/master/so.dom.js#L426"
if (st > lastScrollTop) {
// downscroll code
} else if (st < lastScrollTop) {
// upscroll code
} // else was horizontal scroll
lastScrollTop = st <= 0 ? 0 : st; // For Mobile or negative scrolling
}, false);
Simple way to catch all scroll events (touch and wheel)
window.onscroll = function(e) {
// print "false" if direction is down and "true" if up
console.log(this.oldScroll > this.scrollY);
this.oldScroll = this.scrollY;
}
Use this to find the scroll direction. This is only to find the direction of the Vertical Scroll. Supports all cross browsers.
var scrollableElement = document.body; //document.getElementById('scrollableElement');
scrollableElement.addEventListener('wheel', checkScrollDirection);
function checkScrollDirection(event) {
if (checkScrollDirectionIsUp(event)) {
console.log('UP');
} else {
console.log('Down');
}
}
function checkScrollDirectionIsUp(event) {
if (event.wheelDelta) {
return event.wheelDelta > 0;
}
return event.deltaY < 0;
}
Example
You can try doing this.
function scrollDetect(){
var lastScroll = 0;
window.onscroll = function() {
let currentScroll = document.documentElement.scrollTop || document.body.scrollTop; // Get Current Scroll Value
if (currentScroll > 0 && lastScroll <= currentScroll){
lastScroll = currentScroll;
document.getElementById("scrollLoc").innerHTML = "Scrolling DOWN";
}else{
lastScroll = currentScroll;
document.getElementById("scrollLoc").innerHTML = "Scrolling UP";
}
};
}
scrollDetect();
html,body{
height:100%;
width:100%;
margin:0;
padding:0;
}
.cont{
height:100%;
width:100%;
}
.item{
margin:0;
padding:0;
height:100%;
width:100%;
background: #ffad33;
}
.red{
background: red;
}
p{
position:fixed;
font-size:25px;
top:5%;
left:5%;
}
<div class="cont">
<div class="item"></div>
<div class="item red"></div>
<p id="scrollLoc">0</p>
</div>
Initialize an oldValue
Get the newValue by listening to the event
Subtract the two
Conclude from the result
Update oldValue with the newValue
// Initialization
let oldValue = 0;
//Listening on the event
window.addEventListener('scroll', function(e){
// Get the new Value
newValue = window.pageYOffset;
//Subtract the two and conclude
if(oldValue - newValue < 0){
console.log("Up");
} else if(oldValue - newValue > 0){
console.log("Down");
}
// Update the old value
oldValue = newValue;
});
This is an addition to what prateek has answered.There seems to be a glitch in the code in IE so i decided to modify it a bit nothing fancy(just another condition)
$('document').ready(function() {
var lastScrollTop = 0;
$(window).scroll(function(event){
var st = $(this).scrollTop();
if (st > lastScrollTop){
console.log("down")
}
else if(st == lastScrollTop)
{
//do nothing
//In IE this is an important condition because there seems to be some instances where the last scrollTop is equal to the new one
}
else {
console.log("up")
}
lastScrollTop = st;
});});
While the accepted answer works, it is worth noting that this will fire at a high rate. This can cause performance issues for computationally expensive operations.
The recommendation from MDN is to throttle the events. Below is a modification of their sample, enhanced to detect scroll direction.
Modified from: https://developer.mozilla.org/en-US/docs/Web/API/Document/scroll_event
// ## function declaration
function scrollEventThrottle(fn) {
let last_known_scroll_position = 0;
let ticking = false;
window.addEventListener("scroll", function () {
let previous_known_scroll_position = last_known_scroll_position;
last_known_scroll_position = window.scrollY;
if (!ticking) {
window.requestAnimationFrame(function () {
fn(last_known_scroll_position, previous_known_scroll_position);
ticking = false;
});
ticking = true;
}
});
}
// ## function invocation
scrollEventThrottle((scrollPos, previousScrollPos) => {
if (previousScrollPos > scrollPos) {
console.log("going up");
} else {
console.log("going down");
}
});
This simple code would work: Check the console for results.
let scroll_position = 0;
let scroll_direction;
window.addEventListener('scroll', function(e){
scroll_direction = (document.body.getBoundingClientRect()).top > scroll_position ? 'up' : 'down';
scroll_position = (document.body.getBoundingClientRect()).top;
console.log(scroll_direction);
});
You can get the scrollbar position using document.documentElement.scrollTop. And then it is simply matter of comparing it to the previous position.
If anyone looking to achieve it with React hooks
const [scrollStatus, setScrollStatus] = useState({
scrollDirection: null,
scrollPos: 0,
});
useEffect(() => {
window.addEventListener("scroll", handleScrollDocument);
return () => window.removeEventListener("scroll", handleScrollDocument);
}, []);
function handleScrollDocument() {
setScrollStatus((prev) => { // to get 'previous' value of state
return {
scrollDirection:
document.body.getBoundingClientRect().top > prev.scrollPos
? "up"
: "down",
scrollPos: document.body.getBoundingClientRect().top,
};
});
}
console.log(scrollStatus.scrollDirection)
I personally use this code to detect scroll direction in javascript...
Just you have to define a variable to store lastscrollvalue and then use this if&else
let lastscrollvalue;
function headeronscroll() {
// document on which scroll event will occur
var a = document.querySelector('.refcontainer');
if (lastscrollvalue == undefined) {
lastscrollvalue = a.scrollTop;
// sets lastscrollvalue
} else if (a.scrollTop > lastscrollvalue) {
// downscroll rules will be here
lastscrollvalue = a.scrollTop;
} else if (a.scrollTop < lastscrollvalue) {
// upscroll rules will be here
lastscrollvalue = a.scrollTop;
}
}
Modifying Prateek's answer, if there is no change in lastScrollTop, then it would be a horizontal scroll (with overflow in the x direction, can be used by using horizontal scrollbars with a mouse or using scrollwheel + shift.
const containerElm = document.getElementById("container");
let lastScrollTop = containerElm.scrollTop;
containerElm.addEventListener("scroll", (evt) => {
const st = containerElm.scrollTop;
if (st > lastScrollTop) {
console.log("down scroll");
} else if (st < lastScrollTop) {
console.log("up scroll");
} else {
console.log("horizontal scroll");
}
lastScrollTop = Math.max(st, 0); // For mobile or negative scrolling
});
This seems to be working fine.
document.addEventListener('DOMContentLoaded', () => {
var scrollDirectionDown;
scrollDirectionDown = true;
window.addEventListener('scroll', () => {
if (this.oldScroll > this.scrollY) {
scrollDirectionDown = false;
} else {
scrollDirectionDown = true;
}
this.oldScroll = this.scrollY;
// test
if (scrollDirectionDown) {
console.log('scrolling down');
} else {
console.log('scrolling up');
}
});
});
Sometimes there are inconsistencies in scrolling behavior which does not properly update the scrollTop attribute of an element. It would be safer to put some threshold value before deciding the scroll direction.
let lastScroll = 0
let threshold = 10 // must scroll by 10 units to know the direction of scrolling
element.addEventListener("scroll", () => {
let newScroll = element.scrollTop
if (newScroll - lastScroll > threshold) {
// "up" code here
} else if (newScroll - lastScroll < -threshold) {
// "down" code here
}
lastScroll = newScroll
})
let arrayScroll = [];
window.addEventListener('scroll', ()=>{
arrayScroll.splice(1); //deleting unnecessary data so that array does not get too big
arrayScroll.unshift(Math.round(window.scrollY));
if(arrayScroll[0] > arrayScroll[1]){
console.log('scrolling down');
} else{
console.log('scrolling up');
}
})
I have self-made the above solution. I am not sure if this solution may cause any considerable performance issue comparing other solutions as I have just started learning JS and not yet have completed my begginer course. Any suggestion or advice from experienced coder is highly appriciated. ThankYou!

Why does my if statement keep running?

I'm trying to make a browser scroll to a point on a page if the page is scrolled down. I'm using jQuery .bind() to bind html to mousewheel. Here's my code:
"use strict";
var scrollpoint = 1;
$(document).ready(function(){
console.log(scrollpoint);
$("#divacon").hide();
$("#divbcon").hide();
$('#div-a').waypoint(function() {
$("#divacon").fadeIn();
var scrollpoint = 2;
console.log("waypoint a reached");
},{context:"#container"});
$('#div-b').waypoint(function() {
$("#divbcon").fadeIn();
console.log("waypoint b reached");
},{context:"#container"});
and
$('html').bind('mousewheel', function(e){
var flag = true;
if(flag) {
if(e.originalEvent.wheelDelta < 0) {
if((scrollpoint == 1)) {
var target = $('#div-a');
target = target.length ? target : $('[name=' + this.hash.slice(1) +']');
var targetoffset = target.offset().top;
console.log(scrollpoint);
$('#container').animate(
{scrollTop: targetoffset},
400,
function(){
var scrollpoint = 2;
console.log(scrollpoint);
}
);
}
else if((scrollpoint = 2)){
//scroll down
console.log('2');
}
else{
//scroll down
console.log('Down');
}
}else {
//scroll up
console.log('Up');
}
//prevent page fom scrolling
flag = false;
}
});
What's happening is that my if statement is being called after the first time, even when flag = false;. What am I doing wrong? The site can be found live at http://wilsonbiggs.com/sandy
I think it has to be
var flag = true; //put the flag out side mouse wheel bind.
$('html').bind('mousewheel', function(e){
if(flag) {
Otherwise each time your even triggers you set flag to true and the following if condition will be satisfied always.

Page scrolls up after certain lines

I have problem when writing around 60 lines here in fiddle
then it start to scroll up !.
what im doing wrong there ? thanks.
I want to always stay scrolled down at bottom.
$chat = $('#chatarea');
$submit = $('#submit');
$input = $('#text')
ENTER = 13;
var addMessage = function(message) {
// create message element
$msg = $('<div>', {class: 'message hidden-message', text: message})
if($input.val().length > 0){
// append element
$chat.append($msg) ;
}
else
{
return false;}
$msg.hide().removeClass('hidden-message') ;
$msg.slideDown(function(){
// animate scroll to bottom
$chat.animate({ scrollTop: $chat.height() })
});
};
$input.on('keydown', function(e){
if(e.keyCode === 13 && $input.val().length < 1 ){
return false;
}
});
$input.on('keyup', function(e){
if(e.keyCode == 13 && $input.val().length > 1 ) {addMessage($input.val());
$input.val('');
}
else if(e.keyCode == 13 && $input.val().length == 1){
$input.val('');
e.preventDefault();
return false;}else{}
});
$submit.on('click', function(){
if($input.val().length > 1) {
addMessage($input[0].value);
$input.val('');
}
});
The Problem:
.holder has a height of 1000px and .chatarea inside it has a height of 90%, so in your script $chat.height() always returns 900, so after 60 lines or so, whenever there's an input it scrolls to 900px and stays there.
Solution:
Use this:
$chat.animate({ scrollTop: $chat.prop("scrollHeight") - $chat.height() })
Or a faster animation:
$chat.animate({ scrollTop: $chat.prop("scrollHeight") - $chat.height() }, 25)
Instead of this:
$chat.animate({ scrollTop: $chat.height() })
Demo http://jsfiddle.net/MYPgE/8/
Problem is within $msg.slideDown function, just comment out $chat.animate({ scrollTop: $chat.height() }) and put this code into the $submit.on click function
$(function () {
$("#chatarea").animate({
scrollTop: $('#chatarea').get(0).scrollHeight}, 1000);});
}
fiddle: http://jsfiddle.net/MYPgE/6/

How to get a MouseWheel Event to fire only once in jQuery?

So I want to fire a function only once every time a user scrolls up or down via the Mousewheel. See: jsFiddle Demo. The issue is that even though I have the e.preventDefault(), the function still fires multiple times.
The goal is for the function to fire only once whenever a user scrolls up or down. Similar to this site.
Here is the code that I have so far:
var sq = {};
sq = document;
if (sq.addEventListener) {
sq.addEventListener("mousewheel", MouseWheelHandler(), false);
sq.addEventListener("DOMMouseScroll", MouseWheelHandler(), false);
} else {
sq.attachEvent("onmousewheel", MouseWheelHandler());
}
function MouseWheelHandler() {
return function (e) {
var e = window.event || e;
var delta = Math.max(-1, Math.min(1, (e.wheelDelta || -e.detail)));
if (delta < 0) {
/* Scroll Down */
e.preventDefault();
console.log("Down. I want this to happen only once");
} else {
/* Scroll Up */
console.log("up. I want this to happen only once");
e.preventDefault();
}
return false;
}
return false;
}
This has helped me:
var isMoving=false;
$(document).bind("mousewheel DOMMouseScroll MozMousePixelScroll", function(event, delta) {
event.preventDefault();
if (isMoving) return;
navigateTo();
});
function navigateTo(){
isMoving = true;
setTimeout(function() {
isMoving=false;
},2000);
}
Basically you have a isMoving variable that is set depending on if your animation or whatever you do is in progress. Even though user scrolls multiple times with mousewheel in one "flick", the function fires only once.
​$(document).ready(function(){
var up=false;
var down=false;
$('#foo').bind('mousewheel', function(e){
if(e.originalEvent.wheelDelta /120 > 0 && up=false) {
up=true;
down=false;
$(this).text('scrolling up !');
}
elseif(e.originalEvent.wheelDelta /120 > 0 && down=false){
down=true;
up=false;
$(this).text('scrolling down !');
}
});
});
And here is a plug in you can use it

Categories