1

Wordpress Site; I am using simple code and anchor to send the user to the top of the page.

<body id="pg-top" <?php body_class(); ?> >

...

<a href="#pg-top">miss something?</a>

This sends the user directly to the top instantly. I want the user to be automatically "scrolled up", sent up the page at a certain speed.

Not sure if I explained this correctly, but I've seen this done on many websites. Gradual scroll back to the top of page on click

user3550879
  • 3,389
  • 6
  • 33
  • 62
  • possible duplicate of [smooth scroll with javascript onclick](http://stackoverflow.com/questions/13016379/smooth-scroll-with-javascript-onclick) – D4V1D May 31 '15 at 06:42

2 Answers2

2

you can use jquery animate function on hyperlink click event.

<a href="javascript:void(0);" onclick="scrolltop();">miss something?</a>

jquery

<script>
  function scrolltop(){
    $("html, body").animate({scrollTop:0}, '500');
   }
</script>

you can change animation speed by changing duration parameter. here in my code it is 500.

Nishit Maheta
  • 6,021
  • 3
  • 17
  • 32
2

This is one way that delegates a click event handler to all elements having .scroll-top. You can use it with links, but also all other elements. Due to the event delegation, this will also work with elements that are later added dynamically by other scripts.

$('body').on('click', '.scroll-top', function (e) {
    $('html, body').animate({ scrollTop: 0 }, 300); // Speed: 0.3 seconds
    e.preventDefault();
});

Now you can attach it to any element like in these examples:

<a class="scroll-top" href="#">top</a>
<span class="scroll-top">top</span>
<h1 class="scroll-top">top</h1>

Example: https://jsfiddle.net/j1uct2z8/

Rudi
  • 2,987
  • 1
  • 12
  • 18
  • can that be written as a function that I can put in my page, with php or – user3550879 May 31 '15 at 07:00
  • Yes. Just put it between a ``. It's Javascript/jQuery, having nothing to do with PHP. – Rudi May 31 '15 at 07:01
  • well it brings people back to the top, but the animation doesn't seem to work, I put it in my tags – user3550879 May 31 '15 at 07:05
  • Make sure jQuery is loaded before that code. Here is a working example: https://jsfiddle.net/j1uct2z8/ – Rudi May 31 '15 at 07:07
  • is it based on a specific jQuery, I am bringing it in through wordless dynamically. It checks and brings in the most up to date jQuery.js – user3550879 May 31 '15 at 07:10
  • That's not a good idea, but this works in all current jQuery versions. In the jsfiddle, you can select a different jQuery version on the left to try out. – Rudi May 31 '15 at 07:17