1

I have a button with class "scrollToTop" that scrolls to the top of the page when clicked on. Here's the js file:

$(document).ready(function(){

  //Check to see if the window is top if not then display button
  $(window).scroll(function(){
    if ($(this).scrollTop() > 100) {
        $('.scrollToTop').fadeIn();
    } else {
        $('.scrollToTop').fadeOut();
    }
  });

  //Click event to scroll to top
  $('.scrollToTop').click(function(){
    $('html, body').animate({scrollTop : 0},800);
    return false;
  });


});

So this button also has a :hover property:

.scrollToTop:hover{
  opacity: 1.0;
  box-shadow: 0 10px 20px rgba(0,0,0,0.25), 0 8px 8px rgba(0,0,0,0.22);
  -webkit-transition: all 0.4s ease-in-out;
  -moz-transition: all 0.4s ease-in-out;
  -o-transition: all 0.4s ease-in-out;
  transition: all 0.4s ease-in-out;
}

Now, as we all know :hover doesn't work well in mobile devices i.e. 1) You have to click on the button to change the opacity to 1.0 & 2) You have to tap elsewhere to change the opacity back to what it was before (let's say, 0.5).

Here, I'm wanting to simulate the 2nd part. I want to edit the jquery such that when the page is scrolled to the top, scrollToTop automatically loses focus, so that it loses the :hover effect and its opacity automatically returns to 0.5 without the user having to tap elsewhere. I hope I made myself clear. Is this possible? If not, are there other ways to get the same result? Thanks in advance!

Arif
  • 712
  • 11
  • 20
  • I think you can just focus on another element. – Idan Magled Jun 28 '16 at 11:37
  • 1
    I think to hanlde all kind of device, you would have better to toggle a class instead of using pseudo class `:hover`. The downside is that logic regarding mouseenter/mouseleave would need to be handled using js/jquery. But that would let you just remove the class when needed. Now i'm wondering if setting `` and then `document.body.focus();` would work or not?! – A. Wolff Jun 28 '16 at 11:53
  • 1
    Other idea to try, remove/readd the `scrollToTop` class. E.g, inside click handler: `$(this).removeClass('scrollToTop').addClass('scrollToTop');`. My last one idea would be to force a redraw, e.g, still in click handler: `$(this).hide().show(0);` – A. Wolff Jun 28 '16 at 11:59

1 Answers1

1

If I've got this right, I think you need to use:

 $('.scrollToTop').blur();

So you can put it in:

$('.scrollToTop').click(function(){
    // Remove focus from the button
    $('.scrollToTop').blur();
    $('html, body').animate({scrollTop : 0},800);        
    return 
});

Alternatively, another StackOverflow question suggests using an ontouchend event then removing and re-appending the element to the dom:

$('.scrollToTop').on('touchend', function(){
    var el = this;
    var par = el.parentNode;
    var next = el.nextSibling;
    par.removeChild(el)
    setTimeout(function() {
        par.insertBefore(el, next);
    },0);
});
Community
  • 1
  • 1
Sinan Guclu
  • 1,075
  • 6
  • 16