Javascript Scroll up and Down buttons - javascript

Im trying to make 2 buttons, one called "up" and one called "down".
Those should when I hold down my mouse on one of them, it should scroll up or down the whole page.
I tried with this code, but it didn't worked well.
Up
down​
<script>
$(document).ready(function() {
$("#down").hover(function () {
scroll_page("down");
}, function() { $('.content').stop(); });
$("#up").hover(function () {
scroll_page("up");
}, function() { $('.content').stop(); });
});
function scroll_page(direction) {
var scrolled = $(window).scrollTop();
if (direction == 'up') {
var scroll = scrolled + 100;
}else{
var scroll = scrolled - 100;
}
$("html, body").animate({ scrollTop: scroll }, "fast");
}
​
</script>
Does anyone have any ideas what to do?

Related

How to listen to only the first scroll event on javascript/jquery?

I'm currently working on implementing my own version of snap-scrolling using vanilla JavaScript, and while I've got it mostly working as of now, I'm having trouble handling the scroll events.
My HTML looks something like this:
<div class="container">
<div id="item1"></div>
<div id="item2"></div>
<div id="item3"></div>
<div id="item4"></div>
</div>
And my JS looks something like this:
var pos = 0;
var isScrolling = false;
var id = 1;
$(window).scroll(function() {
if (!isScrolling) {
isScrolling = true;
var curPos = $(this).scrollTop();
if (curPos > pos) {
// scrolling down
if (id < 4) {
id++;
$('html, body').animate({
scrollTop: $('#item' + id).offset().top
}, 500);
}
} else {
// scrolling up
if (id > 1) {
id--;
$('html, body').animate({
scrollTop: $('#item' + id).offset().top
}, 500);
}
}
isScrolling = false;
pos = curPos;
}
});
What currently happens is when I scroll down my mouse wheel, it will do the animation but will keep proceeding to the next divs because of the multiple scroll events being fired. How do I make it so that it only listens to the first event (whether it scrolls up or down)?
A hacky way is to use timer:
var pos = 0;
var isScrolling = false;
var id = 1;
var lastScrollTime = $.now();
$(window).scroll(function() {
if ((!isScrolling)&&((($.now()-lastScrollTime)>3000)) {
isScrolling = true;
var curPos = $(this).scrollTop();
if (curPos > pos) {
// scrolling down
if (id < 4) {
id++;
$('html, body').animate({
scrollTop: $('#item' + id).offset().top
}, 500);
}
} else {
// scrolling up
if (id > 1) {
id--;
$('html, body').animate({
scrollTop: $('#item' + id).offset().top
}, 500);
}
}
isScrolling = false;
pos = curPos;
lastScrollTime = $.now();
}
});
You can register one time listeners in jQuery using jQuery.one.
EDIT:
You can use the complete callback of jQuery.animate to stop/start responding to scroll events.
var isScrolling = false;
$(window).on('scroll', function () {
if (!isScrolling) {
isScrolling = true;
var curPos = $(this).scrollTop();
if (curPos > pos) {
// scrolling down
if (id < 4) {
id++;
$('html, body').animate({
scrollTop: $('#item' + id).offset().top
}, 500,function(){
isScrolling = false;
});
}
} else {
// scrolling up
if (id > 1) {
id--;
$('html, body').animate({
scrollTop: $('#item' + id).offset().top
}, 500,function(){
isScrolling = false;
});
}
}
pos = curPos;
}
});
There's no easy way to deal with what it is known as kinetic scrolling.
Browsers do not provide developers a proper way to distinguish the meaningful scrolling from the inertial ones.
However, there are some attempts out there that aims to solve this issue, such as Lethargy.
Not 100% ideal, but very close to it.
Other than that, you can take a look at libraries like fullPage.js where another attempt to solve the issue was made.

Scroll to bottom of page using Javascript or jquery with these conditions

I am trying to stimulate a web chat room for which the page needs to be:
Scrolled to bottom of the page after some interval if the user hasn't scrolled.
Stop scrolling if the user has scrolled.
Starts scrolling to bottom of page if user reaches a div #end
<script>
var scroll = 1;
function autoScrolling(scroll) {
if(scroll==1){
window.scrollTo(0,document.body.scrollHeight);
}
}
window.onscroll = function() {
setInterval(autoScrolling(0), 1000);
}
window.addEventListener("scroll", function() {
var elementTarget = document.getElementById("end");
if (window.scrollY > (elementTarget.offsetTop + elementTarget.offsetHeight)) {
scroll=1;
setInterval(autoScrolling(0), 1000);
}
});
</script>
I am applying this logic but it isn't working.
Try this,
var scrolled = false;
$(document).ready(function(){
//First requirement
window.setInterval(function(){
checkScroll();
}, 5000);
//Second requirement
window.onscroll = function() { setScroll()};
//Third requirement
$('#end').on('scroll', function() {
if($(this).scrollTop() + $(this).innerHeight() >= $(this)[0].scrollHeight) {
autoScroll();
}
})
})
function autoScroll(){
window.scrollTo(0,document.body.scrollHeight);
}
function setScroll(){
if (window.scrollY > (elementTarget.offsetTop + elementTarget.offsetHeight)) {
scroll=true;
}
}
}
function checkScroll(){
if(!scrolled)
autoScroll();
scrolled = false;
}

jQuery scrollTop() returns wrong offset on scroll-direction change

I'm trying to get the correct scroll direction via jQuery's "scroll" event.
For this, I'm using the solution here: https://stackoverflow.com/a/4326907/8407840
However, if I change the direction of my scroll, the offset returned by scrollTop is incorrect on the first time. This results in the following behavior:
Wheel down -> down
Wheel down -> down
Wheel up -> down
Wheel up -> up
Wheel down -> up
Wheel down -> down
... and so on, I think you get it.
var ACTIVE_SECTION = null;
var ANIMATION_DURATION = 700;
$(document).ready(function() {
ACTIVE_SECTION = $("section:first-of-type").get(0);
var prevPosition = $(window).scrollTop();
$(window).on("scroll", function() {
doScrollingStuff(prevPosition);
});
});
function doScrollingStuff(prevPosition) {
var ctPosition = $(window).scrollTop();
var nextSection = ACTIVE_SECTION;
// Remove and re-append event, to prevent it from firing too often.
$(window).off("scroll");
setTimeout(function() {
$(window).on("scroll", function() {
doScrollingStuff(prevPosition);
});
}, ANIMATION_DURATION + 100);
// Determine scroll direction and target the next section
if(ctPosition < prevPosition) {
console.log("up");
nextSection = $(ACTIVE_SECTION).prev("section").get(0);
} else if(ctPosition > prevPosition) {
console.log("down");
nextSection = $(ACTIVE_SECTION).next("section").get(0);
}
// If a next section exists: Scroll to it!
if(typeof nextSection != 'undefined') {
var offset = $(nextSection).offset();
$("body, html").animate({
scrollTop: offset.top
}, ANIMATION_DURATION);
ACTIVE_SECTION = nextSection;
} else {
nextSection = ACTIVE_SECTION;
}
console.log(ACTIVE_SECTION);
prevPosition = ctPosition;
}
section {
width:100%;
height:100vh;
padding:60px;
box-sizing:border-box;
}
section:nth-child(1) { background:#13F399; }
section:nth-child(2) { background:#14FD43; }
section:nth-child(3) { background:#4EE61E; }
section:nth-child(4) { background:#BEFD14; }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<section id="sect1">Section 1</section>
<section id="sect2">Section 2</section>
<section id="sect3">Section 3</section>
<section id="sect4">Section 4</section>
Here's a pen, where you can see my implementation: https://codepen.io/EigenDerArtige/pen/aVEyxd
I am trying to accomplish an autoscroll to the next or previous section, whenever the user scrolls or swipes up/down... Therefore I only fire the "scroll"-event once every second, to prevent multiple scrolljacks all happening at once... However the above behavior seems to result in the user being scrolled to the wrong section.
I've been trying for a couple of hours now to get it working, but to no avail. Help is greatly appreciated!
The problem lies in the assignment prevPosition = ctPosition.
Each time the scroll handler runs, var ctPosition = $(window).scrollTop(); is good for determining scroll direction, however it's not the value that should be rememberad as prevPosition.
prevPosition needs to be $(window).scrollTop() as measured after the animation has completed.
Try this :
$(document).ready(function() {
var ANIMATION_DURATION = 700;
var ACTIVE_SECTION = $("section:first-of-type").eq(0);
var prevPosition = $(window).scrollTop();
$(window).on("scroll", doScrollingStuff);
function doScrollingStuff(e) {
$(window).off("scroll");
var ctPosition = $(window).scrollTop();
var nextSection = (ctPosition < prevPosition) ? ACTIVE_SECTION.prev("section") : (ctPosition > prevPosition) ? ACTIVE_SECTION.next("section") : ACTIVE_SECTION; // Determine scroll direction and target the next section
// If next section exists and is not current section: Scroll to it!
if(nextSection.length > 0 && nextSection !== ACTIVE_SECTION) {
$("body, html").animate({
'scrollTop': nextSection.offset().top
}, ANIMATION_DURATION).promise().then(function() {
// when animation is complete
prevPosition = $(window).scrollTop(); // remember remeasured .scrollTop()
ACTIVE_SECTION = nextSection; // remember active section
$(window).on("scroll", doScrollingStuff); // no need for additional delay after animation
});
} else {
setTimeout(function() {
$(window).on("scroll", doScrollingStuff);
}, 100); // Debounce
}
}
});

JS Smooth Scroll Vertical & Horizontal Function

I want to create a multisite in a one-page, where everytime a link is clicked, it automatically scrolls to that element in the page (all div elements).
The function works but it still jumps to the given element.
Here's the code I've got so far and the elements I use to call the function:
<li class="topli">
<a id="toplink" onclick="Scroll('#home')" href="javascript:void(0);">HOME</a>
</li>
<script>
function Scroll(element) {
var ID = element.split('#').join('');
var target = document.getElementById(ID);
var offset = target.getBoundingClientRect();
console.log("X:",offset.x,"Y:",offset.y);
if (window.scrollY != offset.y) {
window.scroll(window.scrollY, offset.y);
}
if (window.scrollX != offset.x) {
window.scroll(window.scrollX, offset.x);
}
}
</script>
If needed I'll add a more detailed code to a JSFiddle.
Create jQuery helper for this
(function($) {
$.fn.goTo = function() {
$('html, body').animate({
scrollTop: $(this).offset().top + 'px'
}, 'fast');
return this;
}
})(jQuery);
And use like
$('#el').goTo();
Try this for scrolling vertically (where 100 is the rate of scroll):
const goTo = (targetEl) => {
const elm = document.querySelector(targetEl);
const offset = elm.getBoundingClientRect().bottom;
if (offset > window.innerHeight) {
window.scroll(0, window.scrollY + 100);
setTimeout(() => {
goTo(targetEl);
}, 16.666);
} else {
return;
}
};
Call it like so:
goTo('#scroll-target');
or on click:
window.addEventListener('DOMContentLoaded', () => {
document.querySelector('.long-div').addEventListener('click', () => {
goTo('#scroll-target');
});
});
Vertical smooth scroll, easy and native way:
let element = document.querySelector('#element');
// Vertical Scroll
this.element.scrollTo({
left: element.offsetLeft,
behavior: 'smooth'
})
// Horizontal Scroll
element.scrollIntoView({block: "end", behavior: "smooth"});
docs:
https://developer.mozilla.org/pt-BR/docs/Web/API/Element/scrollIntoView
https://developer.mozilla.org/en-US/docs/Web/API/Element/scrollTo

vertical slider on scroll

i am searching for a slider which should change the slides vertically on scroll.
This is the refrence Url : https://www.uber.com/ The Mobile slider
Please help me,i am trying to do this since7,8 hours.
this is the code i am trying to use.
$(document).ready(function() {
// var totalheight=$(window).height();
// $('.carosel-section').css('height',totalheight);
//Set each section's height equals to the window height
//$('.moveable').height($(window).height());
$('.moveable').first().addClass('active');
$('.carousel-wrap').on('mousewheel DOMMouseScroll', function (e) {
e.preventDefault();//prevent the default mousewheel scrolling
var active = $('.moveable.active');
var delta = e.originalEvent.detail < 0 || e.originalEvent.wheelDelta > 0 ? 1 : -1;
if (delta < 0) {
//mousewheel down handler
next = active.next();
if (next.length) {
var timer = setTimeout(function () {
$('body, html').animate({
scrollTop: next.offset().top
}, 'fast');
// move the indicator 'active' class
next.addClass('active')
.siblings().removeClass('active');
clearTimeout(timer);
}, 100);
}
} else {
prev = active.prev();
if (prev.length) {
var timer = setTimeout(function () {
$('body, html').animate({
scrollTop: prev.offset().top
}, 'slow');
prev.addClass('active')
.siblings().removeClass('active');
clearTimeout(timer);
}, 800);
}
}
});
});
Have you tried looking at Parallax.js? I think that is what you are looking for. The examples on the main page should give you a quick start!

Categories

Resources