I have a button that scrolls to another element. This works fine on desktop but on mobile if I scroll a little bit and click the button, the function does not scroll precisely to the element I want but is a bit off, even though I didn't specify any offset.
On desktop I have a fixed menu that changes size, so that is why in below code I check for desktop or mobile using the window width:
if(window.outerWidth > 991) {
console.log('desktop');
$("body").on("click","#bestellenbtn",function(){
var scrollmenuheight = $('.scrollmenu').height();
$([document.documentElement, document.body]).animate({
scrollTop: $("#bestellen").offset().top - scrollmenuheight
}, 1000);
});
}else{
console.log('mobile');
$("body").on("click","#bestellenbtn",function(){
$([document.documentElement, document.body]).animate({
scrollTop: $("#bestellen").offset().top
}, 1000);
});
}
This is the button that starts the function:
<a href="javascript:void(0);" id="bestellenbtn"><button class="btnstyle blue-inverse" type="button" name="button">Bestellen</button></a>
And the element:
<div class="separator" id="bestellen">
<div class="container">
<div class="row">
<div class="col-md-12">
<h2>Bestellen</h2>
</div>
</div>
</div>
</div>
I added a copy of the page in a codepen so you can see it for yourself (click the first of 4 blue buttons on mobile view):
https://codepen.io/twan2020/pen/RwGmaMQ You can resize to get the mobile version.
What can I do?
I've tried changing the offset but that shouldn't be necessary because on mobile there is no fixed menu that changes the height of the document.
I made a short video to show what the problem is:
https://gyazo.com/431163072afb0de9a6488ebfba895ff5
question from:
https://stackoverflow.com/questions/65848336/scrolltop-function-not-working-correctly-when-scrolling-on-mobile 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…