0

I was creating a dummy back to top button when it turns out that my jQuery call to fadeOut() acts differently on mobiles (the difference of issue can be reproduced with any desktop browser simulator).

The source code is there: https://codepen.io/ehouarn-perret/pen/ZRgJXE

But basically there is the setup below (called 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; 
    }); 
};

with a button which has the CSS below:

#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 difference between the two calls is that on the mobile / tablet version, the hover state is maintained (i.e. background-color: #9c0909;, opacity: 1).

Any reason about why this behaviour is occurring?

Solution:

As mentioned in the accepted answer, this is due to the sticky behaviour on touch devices, after reading this article http://www.hnldesign.nl/work/code/mouseover-hover-on-touch-devices-using-jquery/ I decided to leverage the touchstart event along the click.

Changing this:

$('#back-to-top-button').click(function(){ 
    $("html, body").animate({ scrollTop: 0 }, 500); 
    return false; 
}); 

To that:

$('#back-to-top-button').on('click touchstart', onBackToTopButtonClick);

Which actually "kinda" makes sense since the hovering state on a touch device results in stickiness.

Natalie Perret
  • 8,013
  • 12
  • 66
  • 129

1 Answers1

2

It's because of sticky hover behaviour on mobile (Its a well known bug/behaviour). :hover state will go away one you touch anywhere else.

Just google "sticky hover mobile" to find some solutions. Here's a SO answer I found : https://stackoverflow.com/a/17234319/9591609

(IMO you shouldn't bother and just let it be. That's what everyone else is doing)

Devansh J
  • 4,006
  • 11
  • 23
  • Thanks! also found this thing here: http://www.hnldesign.nl/work/code/mouseover-hover-on-touch-devices-using-jquery/ touchStart event – Natalie Perret Jul 07 '18 at 19:55