Search code examples
javascriptjquerygreasemonkey

Greasemonkey - integrating scroll and mouse click action


I have a bunch of links on a page where I am playing a game.

The requirement is to scroll to the link and click on it. I have managed to click on it.

function clickLinkWithText () {
    var links = $('a[href*="xyz.com"]');
    var randomNum = Math.floor(Math.random()*links.length);   
    var targetLink = links.get(randomNum);
    triggerMouseEvent (targetLink, "click"); 
}

But first, how do I scroll to the element and then click on it. What should I change here?

function scrollToElement() {    
   window.setTimeout("window.scrollTo(0, document.body.offsetHeight);", 
   1000);
};

window.addEventListener('mouseover',function() {
    scrollToElement()
},true);

Solution

  • In most browsers you can scroll to an element by calling scrollIntoView() on it. Then, you can set a small timeout (so that the browser has time to scroll to the element), after which you can click on the element. For example, the following userscript will scroll to your username and click it:

    // ==UserScript==
    // @name         scroll-click
    // @namespace    CertainPerformance
    // @version      1
    // @match        https://stackoverflow.com/questions/52341101/greasemonkey-integrating-scroll-and-mouse-click-action
    // @grant        none
    // ==/UserScript==
    
    const a = document.querySelector('a[href="/users/1089173/curiousdev"]');
    
    function scrollToElement() {
      a.scrollIntoView();
      setTimeout(() => {
        a.click();
      }, 1000);
    };
    
    window.addEventListener('mouseover', scrollToElement);
    

    Note that there's no need for jQuery, and that you can pass the function name directly to addEventListener rather than wrapping it in another anonymous function.

    Also, try to avoid ever passing strings to setTimeout - that's basically the same as eval. Better to pass an actual function.