Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to scrollTop when html, body is set to height: 100%?

The following won't work unless I remove height: 100% from body and html. However, i need that style as I am using it for other elements on the page.

html

<a href="#" id="scrollTop">Back to top</a>

jQuery

$("#scrollTop").on("click",function(e){
  e.preventDefault();
  $(window).animate({scrollTop: 0}, 'slow');
});

Even tried the following with still negative results

$("#scrollTop").on("click",function(e){
  e.preventDefault();
  $("body, html").animate({scrollTop: 0}, 'slow');
});

Css

html, body {height:100%; min-height:100%;}
like image 208
rob.m Avatar asked Jan 14 '14 21:01

rob.m


2 Answers

Got the issue, thanks to comments I noticed I had body: overflow-x:hidden which means scrollTop isn't working when we are using overflow on body, html

like image 170
rob.m Avatar answered Oct 21 '22 23:10

rob.m


I had the same problem with body { height: 100%; } and scrollTop(0).

Since I was not able to change html/css for different reasons, workaround was to remove height before scrollTop, and then revert to initial state.

// Change height:100% into auto
$('body').css('height', 'auto');
// Successfully scroll back to top
$('body').scrollTop(0);
// Remove javascript added styles
$('body').css('height', '');
like image 28
Matija Mrkaic Avatar answered Oct 21 '22 22:10

Matija Mrkaic