I have a page with some checkboxes items and then a textarea
element at very bottom of the page. This textarea
has no autofocus assigned.
<textarea id="comments" class="form-control" rows="8">@Comments</textarea>
textarea
always get focus when page loads and scroll to bottom itself.
It has to be working for Android and iPhone webview containers.
I have tried a lot to scroll to top after page loads or remove the focus from this element but no luck so far.
I have tried below different tricks I found here:
$("html,body").animate({ scrollTop: 0 }, "slow");
$(this).scrollTop(0);
$('textarea').blur();
$('#comments').blur();
document.activeElement.blur();
document.getElementById("origin").focus();
$('html,body').animate({
scrollTop: $("#origin").offset().top
});
$("body").scrollTop(0);
document.body.scrollTop = 0;
document.documentElement.scrollTop = 0;
even button go to top click not working
$("#myBtn").on("click", function () {
console.log('ddd');
$(this).scrollTop(0);
$("html").scrollTop(0);
document.body.scrollTop = 0;
document.documentElement.scrollTop = 0;
});
I also found it could be because of overflow: scroll on main container which could preventing scrolltotop
from working.
so here is my main container details from _Layout.chtml page.
#mobile-content-wrapper {
position: relative;
width: 100%;
padding-bottom: 80px;
overflow-y: scroll;
overflow-x: hidden;
I could use some of your experience here.
The android scrollTop workaround would be:
on some older versions of the android browser, setting scrollTop would be ignored if the overflow was not 'hidden' (which is definitely a browser bug).
That said, I didn't test that on the body element. The bug presents itself on any DOM element with overflow which is where I discovered the workaround. I haven't encountered this bug in many years though, as the older android browsers are pretty rare and aren't supported in my current projects.
Also, trying to fix your issue by the use of scrollTop seems wrong. You should try to fix the reason that your element is receiving focus and scrolling your window on launch in the first place. I can't help you with that without seeing a running website with the issue. If you could create a jsfiddle or equivalent that reproduces the issue I'm happy to take a look at it.
Actually I was able to hack it. Basically I made the textarea readonly on page load. so it wont get focus. And then setting it to enable again after a timeout. This way textbox will be enabled by the time user starts to scroll down.
setTimeout(function () { document.getElementById('comments').readOnly = false }, 500);