Reputation: 1259
Is there a way to increase a variable as the user scrolls up, and decrease when the user scrolls down with JavaScript? There is no maximum or minimum value for the variable, and it would be nice to be able to adjust the sensitivity. I have no idea where to begin, thanks for the help!
EDIT: There is no scroll bar because the content of the page fits in the screen with nothing extra. Sorry if this caused any confusion.
Upvotes: 1
Views: 3220
Reputation: 18
$("document").ready(function(){
$(window).scroll(function(){
let scrollValue = window.scrollY;
let num = $("#num");
num.html(scrollValue);
});
});
body {
height: 2000px;
text-align: center;
}
p {
position: fixed;
font-size: 70px;
top: 0;
}
<script
src="https://code.jquery.com/jquery-3.3.1.min.js"
integrity="sha256-FgpCb/KJQlLNfOu91ta32o/NMZxltwRo8QtmkMRdAu8="
crossorigin="anonymous"></script>
<p>Scroll to view <span id="num"></span></p>
Upvotes: 0
Reputation: 2324
You can use window.scrollY
. It's the distance in pixels from the top of the screen, so if you do -window.scrollY
to get it to increase as they scroll up and decrease (become more negative) as they scroll down, like you asked for.
If you want to adjust sensitivity, you could divide it by something arbitrary (in this example, 5
):
function getAdjustedScroll() {
const DIVIDE_AMOUNT = 5;
return -window.scrollY / DIVIDE_AMOUNT;
}
You can also use the wheel
event to detect wheel movements on a non-scrolling page.
Using a similar example to the original:
let scrollAmount = 0;
document.addEventListener('wheel', (event) => {
const DIVIDE_AMOUNT = 5;
scrollAmount += event.deltaY / DIVIDE_AMOUNT;
});
Upvotes: 2
Reputation: 31712
I think you are looking for the wheel event. This event is fired when you rotate the mousewheel or similar devices as when you do to scroll for example. Here is an example of how to use it:
var testDiv = document.getElementById("test-div");
var amount = 0;
document.addEventListener("wheel", function(ev) {
amount += ev.deltaY;
testDiv.textContent = amount;
});
<div id="test-div">SCORLL!</div>
Notes:
ev.deltaY
with a number that represent the sensitivity: amount += 0.5 * ev.delta;
for example.var testDiv = document.getElementById("test-div");
var amount = 0;
document.addEventListener("wheel", function(ev) {
amount += ev.deltaY;
testDiv.textContent = 1000 * amount;
});
<div id="test-div">SCORLL!</div>
ev.preventDefault()
. The amount
variable will still change but the scrolling of the page won't occur.var testDiv = document.getElementById("test-div");
var amount = 0;
document.addEventListener("wheel", function(ev) {
amount += ev.deltaY;
testDiv.textContent = amount;
ev.preventDefault();
});
<div id="test-div">SCORLL!</div>
Upvotes: 1
Reputation: 325
yes there is. by use of getBoundingClientRect(); method which has 4 options:- top,left,bottom and right.further reading: https://developer.mozilla.org/en-US/docs/Web/API/Element/getBoundingClientRect
Upvotes: 0