0

I have tried to get this to work and was unsuccessful. I just want to have my mobile page views load at the top. I have tried the following.

// Method 1:
$('body').scrollTop(0);

// Method 2:
document.body.scrollTop = 0;

// Method 3:
$(window).on('beforeunload', function(){
  $(window).scrollTop(0);
});

I tried here first and was unsuccessful.

I just want to always start at the top of the page when I click a link in mobile. I have no idea as to why none of these solutions work.

Community
  • 1
  • 1
riotgear
  • 451
  • 1
  • 5
  • 19

2 Answers2

2

You can use also vanilla JS for it:

document.body.scrollTop = document.documentElement.scrollTop = 0;

or with JQuery

$(document).ready(function() {
    $(this).scrollTop(0);
});

Try also

$('html,body').scrollTop(0);

Check this demo as well, might help https://jsfiddle.net/a_incarnati/v575uvyb/2/

Alessandro Incarnati
  • 7,018
  • 3
  • 38
  • 54
1

You should include $(this).scrollTop(0); within a $(document).ready(); call, like so:

$(document).ready(function() {
    $(this).scrollTop(0);
});

In your code, you are calling $(this).scrollTop(0); before the page unloads, rather than after the page and DOM have been reloaded.

Community
  • 1
  • 1
Ninjakannon
  • 3,751
  • 7
  • 53
  • 76
  • What happens instead? Are you sure the function is being called? – Ninjakannon Apr 15 '15 at 20:49
  • I am sure because the alert loads. When I scroll halfway down the page then click to go to a new page it stays at the same vertical position instead of starting at the top. – riotgear Apr 15 '15 at 20:50
  • Are you loading new page content in to the same page via AJAX, or truly loading a new page? – Ninjakannon Apr 15 '15 at 20:52