OnMouseScroll increment a variable JS - javascript

I want to make a JS function.
It will work like this :
If I use my Mouse Wheel to Scroll Down so my variable will decrement. And if I use my Mouse Wheel to Scroll Up my variable will increment
I want to put that in a Condition with a max and min number.
I will send you a screenshot of my website and you will understand
So like you see, I need to make it work without scrollbar. I've only one page in 100vh.
I've make something very bad but you will understand the idea
https://jsfiddle.net/tuzycreo/
i= 1;
if (i>0 && i<5) {
//if(MouseScrollUp)
//i++;
document.querySelector('.number').innerHTML = i;
//else if(MouseScrollDown)
//i--;
// document.querySelector('.number').innerHTML = number;
}
Thanks you guys !

You can try like this,
var scrollCount = 0,
latestScrollTop = 0,
doc = document.documentElement,
top = 0;
// Bind window scroll event
$(window).bind('scroll', function (e) {
top = (window.pageYOffset || doc.scrollTop) - (doc.clientTop || 0);
if (latestScrollTop < top) {
// Scroll down, increment value
scrollCount += 1;
} else {
// Scroll up, decrement value
scrollCount -= 1;
}
// Store latest scroll position for next position calculation
latestScrollTop = top;
});

I make something that is working for me
https://jsfiddle.net/u93c9eth/2/
var scrollCount = 1;
window.addEventListener('mousewheel', function(e){
if(e.wheelDelta<0 && scrollCount<5){
scrollCount++;
}
else if(e.wheelDelta>0 && scrollCount>1){
scrollCount--;
}
document.querySelector('.number').innerHTML = scrollCount;
});

Related

Pause at top and bottom continuous vertical scroll HTML

I have an embedded HTML page containing a single table of event results. I have found the code below which perfectly gives a continuous scroll, however I which to be able to pause for say 10 seconds at both the top and bottom before continuing.
How do I intercept the top and bottom and insert the pause?
Any suggestions would be much appreciated.
/*
Advanced window scroller script-
By JavaScript Kit (www.javascriptkit.com)
Over 200+ free JavaScripts here!
*/
var currentpos = 0, alt = 1, curpos1 = 0, curpos2 = -1
function initialize() {
startit()
}
function scrollwindow() {
if (document.all)
temp = document.body.scrollTop
else
temp = window.pageYOffset
if (alt == 0)
alt = 1
else
alt = 0
if (alt == 0)
curpos1 = temp
else
curpos2 = temp
if (curpos1 != curpos2) {
if (document.all)
currentpos = document.body.scrollTop + 300
else
currentpos = window.pageYOffset + 1
window.scroll(0, currentpos)
}
else {
currentpos = 0
window.scroll(0, currentpos)
}
}
function startit() {
setInterval("scrollwindow()", 25)
}
window.onload = initialize
Since setInterval is a basic javascript function, which runs a function every n-seconds, you set a global variable to capture that "interval", then cancel it when the user performs some action (click on a button). Then resubmit the setInterval to start running in the future, or tie it back to another onClick event. An example would be to have a button that will toggle the setInterval on and off, which will act as a pause/run.
Below is an example of how you could set this up. I have not tested it, so there may be some use cases that could cause issues.
var myInterval = null;
function startit() {
myInterval = setInterval("scrollwindow()", 25)
}
Then to cancel the interval:
function stopInterval() {
clearInterval(myInterval);
myInterval = null;
}
Example of how to toggle the interval on and off:
function toggleInterval() {
if ( myInterval ) {
stopInterval();
}
else {
startit();
}
}
Then just add it to any html element, or a button. This example is assuming the css is locked at the top of the scrollable pane so the user could always have access to click it.
<span onClick="toggleInterval()">Click to pause/continue scrolling.</span>
<button onClick="toggleInterval()">Pause/Scroll</button>

trying to achieve some effect on the background when page scrolling

I'm trying to achieve this effect here in the header, that make the background go up and down when scrolling
here is the example
https://frix.themes95.com/
here what I've tried
https://stackblitz.com/edit/angular-ivy-yzx998?file=src%2Fapp%2Fapp.component.ts
it almost does the required but there is something goes wrong when I'm trying to scroll up
You're forgetting to set your lastScrollTop variable after each scroll event, so it always thinks you're scrolling down. Just put this.lastScrollTop = st; as your last line in the onScroll function like this:
onScroll(event) {
const st = window.pageYOffset || document.documentElement.scrollTop;
if (st > this.lastScrollTop) {
this.pxToMove -= 3;
this.background.nativeElement.style.transform = `translateY(${this.pxToMove}px)`;
} else {
this.pxToMove += 3;
this.background.nativeElement.style.transform = `translateY(${this.pxToMove}px)`;
}
this.lastScrollTop = st;
}
Here's a way to condense this function and have it change position based on how far you've scrolled.
onScroll(event) {
const st = window.pageYOffset || document.documentElement.scrollTop;
// Move the image by the difference between the old and new scrollTop
this.pxToMove -= (st-this.lastScrollTop);
this.background.nativeElement.style.transform = `translateY(${this.pxToMove}px)`;
// Set the previous scrollTop
this.lastScrollTop = st;
}

Creating a simple "smooth scroll" (with javascript vanilla)

I have been trying to make a simple "smoothscroll" function using location.href that triggers on the mousewheel. The main problem is that the EventListener(wheel..) gets a bunch of inputs over the span of ca. 0,9 seconds which keeps triggering the function. "I only want the function to run once".
In the code below I have tried to remove the eventlistener as soon as the function runs, which actually kinda work, the problem is that I want it to be added again, hence the timed function at the bottom. This also kinda work but I dont want to wait a full second to be able to scroll and if I set it to anything lover the function will run multiple times.
I've also tried doing it with conditions "the commented out true or false variables" which works perfectly aslong as you are only scrolling up and down but you cant scroll twice or down twice.
window.addEventListener('wheel', scrolltest, true);
function scrolltest(event) {
window.removeEventListener('wheel', scrolltest, true);
i = event.deltaY;
console.log(i);
if (webstate == 0) {
if (i < 0 && !upexecuted) {
// upexecuted = true;
location.href = "#forside";
// downexecuted = false;
} else if (i > 0 && !downexecuted) {
// downexecuted = true;
location.href = "#underside";
// upexecuted = false;
}
}
setTimeout(function(){ window.addEventListener('wheel', scrolltest, true); }, 1000);
}
I had hoped there was a way to stop the wheel from constantly produce inputs over atleast 0.9 seconds.
"note: don't know if it can help in some way but when the browser is not clicked (the active window) the wheel will registre only one value a nice 100 for down and -100 for up"
What you're trying to do is called "debouncing" or "throttling". (Those aren't exactly the same thing, but you can look up the difference in case it's going to matter to you.) Functions for this are built into libraries like lodash, but if using a library like that is too non-vanilla for what you have in mind, you can always define your own debounce function: https://www.geeksforgeeks.org/debouncing-in-javascript/
You might also want to look into requestanimationframe.
a different approach
okey after fiddeling with this for just about 2 days i got fustrated and started over. no matter what i did the browsers integrated "glide-scroll" was messing up the event trigger. anyway i decided to animate the scrolling myself and honestly it works better than i had imagined: here is my code if anyone want to do this:
var body = document.getElementsByTagName("BODY")[0];
var p1 = document.getElementById('page1');
var p2 = document.getElementById('page2');
var p3 = document.getElementById('page3');
var p4 = document.getElementById('page4');
var p5 = document.getElementById('page5');
var whatpage = 1;
var snap = 50;
var i = 0;
// this part is really just to read what "page" you are on if you update the site. if you add more pages you should remember to add it here too.
window.onload = setcurrentpage;
function setcurrentpage() {
if (window.pageYOffset == p1.offsetTop) {
whatpage = 1;
} else if (window.pageYOffset == p2.offsetTop) {
whatpage = 2;
} else if (window.pageYOffset == p3.offsetTop) {
whatpage = 3;
} else if (window.pageYOffset == p4.offsetTop) {
whatpage = 4;
} else if (window.pageYOffset == p5.offsetTop) {
whatpage = 5;
}
}
// this code is designet to automaticly work with any "id" you have aslong as you give it a variable called p"number" fx p10 as seen above.
function smoothscroll() {
var whatpagenext = whatpage+1;
var whatpageprev = whatpage-1;
var currentpage = window['p'+whatpage];
var nextpage = window['p'+whatpagenext];
var prevpage = window['p'+whatpageprev];
console.log(currentpage);
if (window.pageYOffset > currentpage.offsetTop + snap && window.pageYOffset < nextpage.offsetTop - snap){
body.style.overflowY = "hidden";
i++
window.scrollTo(0, window.pageYOffset+i);
if (window.pageYOffset <= nextpage.offsetTop + snap && window.pageYOffset >= nextpage.offsetTop - snap) {
i=0;
window.scrollTo(0, nextpage.offsetTop);
whatpage += 1;
body.style.overflowY = "initial";
}
} else if (window.pageYOffset < currentpage.offsetTop - snap && window.pageYOffset > prevpage.offsetTop + snap){
body.style.overflowY = "hidden";
i--
window.scrollTo(0, window.pageYOffset+i);
if (window.pageYOffset >= prevpage.offsetTop - snap && window.pageYOffset <= prevpage.offsetTop + snap) {
i=0;
window.scrollTo(0, prevpage.offsetTop);
whatpage -= 1;
body.style.overflowY = "initial";
}
}
}
to remove the scrollbar completely just add this to your stylesheet:
::-webkit-scrollbar {
width: 0px;
background: transparent;
}

How to count mouse wheel scroll in jquery

How to count mouse scroll in jquery/javascript?
Like initial value 0 and scroll down ++1 and scroll up --1.
And not be -1. Must be positive.
If i scroll 2 times down then value will be 2 and then scroll one time up then value be 1.
$(document).ready(function(){
var scrollPos = 0;
var Counter = 0;
$(window).scroll(function(){
var scrollPosCur = $(this).scrollTop();
if (scrollPosCur > scrollPos) {
Counter -= 1;
} else {
Counter += 1;
}
scrollPos = scrollPosCur;
});
});
The code compares the position of a scrollbar. scrollPos shows how many pixels you moved the scrollbar downwards and is initialized with a value of 0, as it starts at the top.
When you scroll the page, scrollPosCur will first save the current Position of the scrollbar. After that we compare how the value changed :
If the current value is bigger than the saved one, it indicates that the scrollbar has been moved downwards, so your Counter is incremented by 1.
Analogous to that, we decrement the Counter by 1 when scrollPosCur is smaller than scrollPos.
In order to keep the code working, we save the current value to compare against for future scroll Events.
Here is a possible solution for your question
var scrollCount = 0,
latestScrollTop = 0,
doc = document.documentElement,
top = 0;
// Bind window scroll event
$(window).bind('scroll', function (e) {
top = (window.pageYOffset || doc.scrollTop) - (doc.clientTop || 0);
if (latestScrollTop < top) {
// Scroll down, increment value
scrollCount += 1;
} else {
// Scroll up, decrement value
scrollCount -= 1;
}
// Store latest scroll position for next position calculation
latestScrollTop = top;
});
scrollcount=0;
$(document).ready(function(){
$("div").scroll(function(){
$("span").text(scrollcount+=1);
});
});
$(window).scroll(function () {
if ($(this).scrollTop() > 100) {
$('.scrollToTop').fadeIn();
} else {
$('.scrollToTop').fadeOut();
}
});
//Click event to scroll to top
$('.scrollToTop').click(function () {
$('html, body').animate({ scrollTop: 0 }, 800);
return false;
});

Javascript "For" Loop not working?

I have a Javascript file that I am using to try to animate a dropdown menu. I have the "Toggle" function in that file set to run when I click on a certain div. Here's the script I'm using:
var up = true;
function Toggle(x)
{
if (up)
{
for (var i = x.offsetTop; i <= 0; i++)
{
x.style.top = i;
if (i == 0)
{
up = false;
}
}
}
else if (up == false)
{
for (var i = x.offsetTop; i >= -50; i--)
{
x.style.top = i;
if (i == -50)
{
up = true;
}
}
}
}
In the HTML div I want to animate, I have the "onclick" property set to "onclick=Toggle(this)". The first for loop works as it should (it sets the div's top offset to 0). However, the second for loop doesn't set the offsetTop. I know that the for loop is activating because I've tested it and it gives me every integer between 0 and -50. Why isn't it setting the offset position?
1) You must specify a unit to the top ie: x.style.top = i +"px"
2) Your function won't animate instead of you use a setInterval or a setTimeout
Like you asked, an example. I wouldn't do it like this for one of my project, but i kept your function to make you more familiar with the code.
I Used setTimeout instead of setInterval because setInterval must be cleared when not needed and setTimeout is just launched one time :
var Toggle = (function() { // use scope to define up/down
var up = true;
return function(element) {
var top = parseInt(element.style.top, 10); // element.offsetTop ?
if ( !top ) {
top = 0;
}
if (up) {
if (element.offsetTop < 0) { // if we are not at 0 and want to get up
element.style.top = (top+1) + "px";
setTimeout(function() { Toggle(element); }, 10); // recall the function in 10 ms
} else { // we change up value
up = !up;
}
}
else {
if (element.offsetTop > -50) {
element.style.top = (top-1) + "px";
setTimeout(function() { Toggle(element); }, 10); // recall the function in 10 ms
} else {
up=!up;
}
}
}
})();
You'd have to use x.style.top = i + 'px' as top and similar css properties must define the type (px, em, %, etc.) unless they are 0, as this is 0 in any case.
But your script would actually snap the div directly to -50px, as you do not wait between those iteration steps.
I'd recommend to use a library like jQuery to use it's animate() method.
function Toggle(obj) {
$(obj).animate({
top: parseInt($(obj).css('top')) === 0 ? '-50px' : '0px'
})
}

Categories

Resources