I’m trying to make a toy script in GreaseMonkey that will cause my screen to repeatedly jump to the top of my screen when I click a button, and stop jumping when I click the button again.
This is my code:
var perpetualScroll = function () {
var scrolling = false;
var scroll = function () {
if (scrolling) {
window.scrollTo(0, 0);
}
};
var scrollDiv = document.createElement("div");
scrollDiv.id = "topScroll0x2a";
scrollDiv.innerHTML = '<a class="topScroll" onclick="scrolling = !scrolling;" style="display:block; position:fixed; bottom: 1em; right: 1em; color:#fff; background-color:#000; padding:.5em;" href="#">Start scroll</a>';
document.body.appendChild(scrollDiv);
var intervalId = window.setInterval(scroll, 50);
};
perpetualScroll();
When I click the button in the lower corner the script creates, it does jump to the top of the screen, but doesn’t continue to perpetually do so.
I’m really new to Javascript and GreaseMonkey, so I’m not quite sure what the problem is. I suspect it might be due to issues in the onclick part of the link, but if it is, I can’t seem to figure it out.
Doing
onclicklike that will not work like you expect. YourinnerHTMLis just a string, so JS has no idea that it is scoped within yourperpetualScrollfunction.onclickhandlers that are strings are evaluated in the global scope, so what you have is equivalent to this:The
scrollingvariable you want is different.You should create an actual function like this:
Obviously setting that CSS is terrible, so you should really put that in a separate stylesheet anyway.