skip to Main Content

I am trying to avoid using element id to click on button so all I need is to scroll down then I click on the button but sometime the page has different hight and I want to avoid that as well ..
The correct hight is about 1200 Y down but as I said some of pages has different hight and 1200 y is not going to help to click the button,
Here is what I did:

window.scrollTo(0,1600);

do{
window.scrollBy(0, -700);
document.getElementsByClassName('button1')[5].click();
i=undefined
}while(i !=undefined);

But I don’t know if I can use nested loop to scroll to the bottom of the page then to go up let say 700 so I can click the button

Thank you.

2

Answers


  1. Chosen as BEST ANSWER

    Folks I've figured it out, all we need is to use "await" after scrolling down and before scrolling up:

    do{
    window.scroll({
        top: 2000
      })
     await new Promise(r => setTimeout(r, 100));
      window.scroll({
        top: -2000
      })
      document.getElementsByClassName('button1')[5].click();
      i=undefined
      }while(i !=undefined);
    

  2. You don’t really have to it with scrollBy(). Just pass the id of the target location in window.location.href.

    make sure you add scroll-behavior: smooth; otherwise it just snap to the bottom.

    html {
      scroll-behavior: smooth;
    }
    
    div {
      height: 200vh;
    }
    <h1>Hello World</h1>
    <button onclick="window.location.href = '#footer'">
            scroll to footer
        </button>
    <div></div>
    <h1 id="footer">footer</h1>
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search