Reputation: 33
I already have this:
var i = 0;
window.onscroll = function (e) {
i = i + 1;
document.write(i.toString())
}
How do I change or add code to make it so that I can repeat this process infinite times, and each time i
gets 1 added.
I need it for my website.
Upvotes: 0
Views: 131
Reputation: 27247
The problem with document.write is that it clears out the contents of the document, so you no longer have any content to scroll. You may notice that you no longer have scrollbars at all! So you have no scroll event either.
If you really want the output to show on the page, then create a place to output to. A disabled input works fine.
fiddle: http://jsfiddle.net/6pNgS/
html:
<input id="scrollcount" type="text" disabled="disabled" value="0" />
javascript:
var i = 0;
var scrollcount = document.getElementById('scrollcount');
window.onscroll = function (e) {
i = i + 1;
scrollcount.value = i.toString();
}
You can test this right here and now. Open your console and run this:
var i = 0;
var scrollcount = $('#answer-22718395 .vote-count-post')[0];
window.onscroll = function (e) {
i = i + 1;
scrollcount.innerHTML = i.toString();
}
Upvotes: 1
Reputation: 2168
That code will run every time a user scrolls if you have enough content on the page to scroll through. Here is a jsFiddle.
var i = 0;
window.onscroll = function (e) {
i = i + 1;
console.log(i);
}
Open developer tools console and you will see that i is incremented and pushed to the console every time you scroll up or down.
Upvotes: 1