While creating a mock back to top button, I encountered an issue with my jQuery call to fadeOut()
behaving differently on mobile devices (this discrepancy can be observed using any desktop browser simulator).
You can find the source code here: https://codepen.io/ehouarn-perret/pen/ZRgJXE
The setup involves the following code snippet (utilized in the jQuery shorthand when the document is ready):
window.setupBackToTopButton = function () {
function updateBackToTopButton() {
if ($(window).scrollTop() > 50) {
$('#back-to-top-button').fadeIn();
} else {
$('#back-to-top-button').fadeOut();
$('#back-to-top-button').blur();
}
}
$(window).on("scroll touchmove", updateBackToTopButton);
updateBackToTopButton();
$('#back-to-top-button').click(function(){
$("html, body").animate({ scrollTop: 0 }, 500);
return false;
});
};
The button comes with the following CSS:
#back-to-top-button {
position: fixed;
right: 10px;
bottom: 10px;
cursor: pointer;
padding: 7px 12px 7px 12px;
background-color: #cc0c0c;
opacity: 0.5;
display: none;
z-index: 9999;
}
#back-to-top-button:hover {
-o-transition: 300ms;
-ms-transition: 300ms;
-moz-transition: 300ms;
-webkit-transition: 300ms;
transition: 300ms;
background-color: #9c0909;
opacity: 1;
}
The issue arises specifically on mobile/tablet versions where the hover state persists (background-color: #9c0909;
, opacity: 1
).
Any insights on why this behavior occurs?
Solution:
As explained in the accepted answer, this behavior relates to the sticky nature of touch devices. After reviewing this article I opted to incorporate the touchstart
event alongside the click.
Replacing this:
$('#back-to-top-button').click(function(){
$("html, body").animate({ scrollTop: 0 }, 500);
return false;
});
With this:
$('#back-to-top-button').on('click touchstart', onBackToTopButtonClick);
This adjustment sort of makes sense as the hovering state on a touch device leads to stickiness.