Reputation: 55
I'm pretty new to web design, and I wanted to make a rectangle which says "true" if the user has scrolled, and turn to "false" after one second has passed.
var hasScroll = false;
$(document).ready(function() {
$(window).scroll(function() {
hasScroll = true;
$("#rectangle").html(hasScroll.toString());
setTimeout(function() {
hasScroll = false;
}, 1000);
});
});
body { height: 800px }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="rectangle"></div>
However, even though the variable "hasScroll" changes exactly how I want, I can't seem to find a way to make the div show the hasScroll status in real-time.
Upvotes: 1
Views: 799
Reputation: 849
It's very simple, Just put the same line $("#rectangle").html(hasScroll.toString());
after setting hasScroll = false;
For ex.,
var hasScroll = false;
$(document).ready(function() {
$(window).scroll(function() {
hasScroll = true;
$("#rectangle").html(hasScroll.toString());
setTimeout(function() {
hasScroll = false;
$("#rectangle").html(hasScroll.toString()); // To show false
}, 1000);
});
});
Upvotes: 0
Reputation: 370679
You'll need to set the #rectangle
's text again after the scrolling is done. You'll also probably want to set/clear a setTimeout
that only runs once no scroll events have been triggered for 1000ms:
let scrollingTimeout;
const rectangle = document.querySelector('#rectangle');
$(window).scroll(function() {
if (scrollingTimeout) clearTimeout(scrollingTimeout);
else rectangle.textContent = 'true';
scrollingTimeout = setTimeout(function() {
console.log('setting text to false');
rectangle.textContent = 'false';
scrollingTimeout = null;
}, 1000);
});
body {
height: 800px
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="rectangle">abc</div>
Upvotes: 2