I am trying to scroll to a specific location in a scrolling DIV. Right now I am using a pixel offset with the jQuery scrollTop() function which works great on desktop brows
These solutions did not work for me. I know someone mentioned mobile detection but their approach did not work for me. It finally dawned on me to use mobile detection to deliver two different CSS styles for each case. Maybe not ideal but it for sure works. Temporarily changing the styles with js also suggested above did not work for me.
I had a two column layout with independently scrolling divs, each set to overflow:scroll and the body had to be set to overflow:hidden. I need to use scrollTop on one of the columns and no solutions worked.
I used wp_is_mobile() (Wordpress function) and if mobile true, overflow: hidden is removed from body and the divs with overflow:scroll have that css removed. Finally, scrollTop worked on mobile.
jQuery(document).ready(function($) {
$(".scroll").click(function(event){
event.preventDefault();
$('html,body').animate({scrollTop:$(this.hash).offset().top}, 1500);
});
});
<a href="#top" class="scroll"></a>
I had the same problem and solved it by using jquery .offset()
instead.
http://api.jquery.com/offset/
$('#yourFineElement').offset({ top: X, left Y)});
A workaound that worked for me: first, temporarily set the overflow property to 'hidden', then set the scrollTop property, then set the overflow property back to 'scroll' (or auto). The scrollTop value seems to be kept intact and honored when the overflow property is set back to 'scroll'. This was a pretty trivial workaround that worked on all browsers I tested on (desktop and mobile). I didn't test it exhaustively, and I didn't test with transitions in place, so there may be side-effects that I haven't encountered... Your mileage may vary - but it's an easy thing to try.
I have a couple solutions for you to try. You will have to test them yourself, as I have not tried them in a mobile browser before, but here they are:
.css()
method (or .animate()
depending on what your eventual goal us) to adjust the top margin (note: you would have to change the overflow to hidden and wrap the text in an inner div, which would be the element whose to margin you are adjusting)top
attribute.Let me know if you need help with any if this or have any more questions about this. Good luck! :)
Note that although I have not tested these in mobile before they are based on CSS standards, not jQuery functions, so they should work.
Try using jQuery's .animate method:
$('.div').animate({ scrollTo: x; });
Where x is equal to the position of the div you want to scroll to the top of.