How to fire scroll using pure javascript?

Asked

Viewed 424 times

2

I would like to know how to implement in pure javascript the same action used with jQuery below:

$('html, body').animate({
   scrollTop: 500
}, 300);

Can anyone tell me what the code would look like?

1 answer

3


Using window.scroll, thus:

window.scroll({top: 500, left: 0, behavior: 'smooth' })

p {height: 40px; vertical-align: middel; border: solid 1px}
<h1>Rolar o html até o final...</h1>
<p>.....</p>
<p>.....</p>
<p>.....</p>
<p>.....</p>
<p>.....</p>
<p>.....</p>
<p>.....</p>
<p>.....</p>
<p>para encher a página...</p>
<p>.....</p>
<p>.....</p>
<p>.....</p>
<p>.....</p>
<p>.....</p>
<p>.....</p>
<p>.....</p>

<input type='button' onclick="window.scroll({top: 500, left: 0, behavior: 'smooth' })" value="clique aqui para executar o scroll" />

In addition, this resource is called "Smooth Scrolling", and is documented in W3C: https://www.w3.org/TR/cssom-view-1/#Smooth-scrolling

  • 2

    Thank you so much @Ricardo

  • I searched the documentation https://developer.mozilla.org/en-US/docs/Web/API/Window/scroll and did not find these parameters there. But that solved my problem. Is there any link you could give me that shows the documentation of window.scroll?

  • 3

    Use window.scrollTo because the window.scroll has become obsolete.

  • 2

    @Miguelbatista added the W3C reference in the reply, and there is also a great link in English: https://hospodarets.com/native_smooth_scrolling

  • 1

    truth @dvd well punctuated

Browser other questions tagged

You are not signed in. Login or sign up in order to post.