Anchor scroll function interferes with scroll event listener logic to hide/show "back to top" button

Viewed 262

I've built a scroll to top button using this method on this page.

I've also written a function that handles scrolling to sections based on an anchor link so that sections are smoothly scrolled into the viewport, taking into consideration the space the navigation takes at the top.

Here's a snippet that reproduces the issue:

const navHeight = 42;
const $scrollTopBtn = $('#scroll-top-btn');

$(window).scroll(function() {
  const scrollTop = $(document).scrollTop();

  if (scrollTop > navHeight) {
    $scrollTopBtn.fadeIn();
  } else {
    $scrollTopBtn.fadeOut();
  }
});

$(document).ready(() => {
  $('a[href*="#"]').on('click', function(event) {
    const hash = this.hash;
    
    if (this.hash) {
      event.preventDefault();

      $('html, body').animate({
        scrollTop: $(hash).offset().top - navHeight,
      }, 350);

      window.location.hash = this.hash;
    }
  });
});
body {
  margin: 0;
  font-family: monospace;
}

nav {
  position: sticky;
  top: 0;
  display: flex;
  background: white;
  border-bottom: 2px solid black;
}

a {
  height: 40px;
  display: flex; 
  align-items: center; 
  padding: 0 8px;
  border-right: 2px solid black;
}

.block {
  min-height: 100vh;
  border-bottom: 2px solid black;
  display: flex; 
  justify-content: center;
  padding: 32px 50vw 32px 32px;
  box-sizing: border-box;
}

#scroll-top-btn {
  position: fixed;
  right: 8px;
  bottom: 8px;
  width: 40px;
  height: 40px;
  border: 2px solid black;
  display: flex; 
  align-items: center;
  justify-content: center;
  padding: 0;
  background: white;
}
<nav>
  <a href="#block1">Block 1</a>
  <a href="#block2">Block 2</a>
  <a href="#block3">Block 3</a>
</nav>

<div id="block1" class="block">
  Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.
</div>

<div id="block2" class="block">
  Sed ut perspiciatis unde omnis iste natus error sit voluptatem accusantium doloremque laudantium, totam rem aperiam, eaque ipsa quae ab illo inventore veritatis et quasi architecto beatae vitae dicta sunt explicabo. Nemo enim ipsam voluptatem quia voluptas sit aspernatur aut odit aut fugit, sed quia consequuntur magni dolores eos qui ratione voluptatem sequi nesciunt. Neque porro quisquam est, qui dolorem ipsum quia dolor sit amet, consectetur, adipisci velit, sed quia non numquam eius modi tempora incidunt ut labore et dolore magnam aliquam quaerat voluptatem. Ut enim ad minima veniam, quis nostrum exercitationem ullam corporis suscipit laboriosam, nisi ut aliquid ex ea commodi consequatur? Quis autem vel eum iure reprehenderit qui in ea voluptate velit esse quam nihil molestiae consequatur, vel illum qui dolorem eum fugiat quo voluptas nulla pariatur?
</div>

<div id="block3" class="block">
  But I must explain to you how all this mistaken idea of denouncing pleasure and praising pain was born and I will give you a complete account of the system, and expound the actual teachings of the great explorer of the truth, the master-builder of human happiness. No one rejects, dislikes, or avoids pleasure itself, because it is pleasure, but because those who do not know how to pursue pleasure rationally encounter consequences that are extremely painful. Nor again is there anyone who loves or pursues or desires to obtain pain of itself, because it is pain, but because occasionally circumstances occur in which toil and pain can procure him some great pleasure. To take a trivial example, which of us ever undertakes laborious physical exercise, except to obtain some advantage from it? But who has any right to find fault with a man who chooses to enjoy a pleasure that has no annoying consequences, or one who avoids a pain that produces no resultant pleasure?
</div>

<button id="scroll-top-btn"></button>

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

On the actual site, the issue only happens sometimes. When an anchor link from the left-hand nav is clicked, the scroll to top button briefly flashes as the page scrolls. It's hard to replicate and doesn't always occur by following the same steps, but it often occurs when first landing on the FAQ page and clicking on the "Troubleshooting" link.

If I don't run the anchor click scroll function, the button doesn't flash.

I don't understand why the button flashes or what it depends on since it should only fade out after the page scrolls more than the nav's height (60px).

I'm also using smoothState.js, which requires me to run functions on $(document).ready and on its own onAfter callback function, but the scroll button listener function only runs on $(window).scroll.

What could be causing the button flashing issue and how can I fix that?

1 Answers

What is happening there is that when you load the page, the scroll position is going to be at the very top. Then, when you click an anchor and your smooth scroll code starts slowly scrolling the page, the scroll listener will be invoked, but the scroll position will still be lower than navHeight, so it will fade out (hide) the #scoll-top-btn button.

Shortly after that, the scroll listener will be invoked again, but this time the scroll position will be higher than navHeight, so it will fade in (show) the #scoll-top-btn button.

You can fix that by checking the scroll direction as well as the scroll position so that the #scoll-top-btn button is only shown when scrolling down or only hidden when scrolling up.

Also, it looks like your #scoll-top-btn button is initially visible, so I would add style="display: none" to it so that it's always hidden when the page loads (but this alone won't fix your issue).

Here you can see how it works with both changes applied:

const navHeight = 42;
const $scrollTopBtn = $('#scroll-top-btn');

let lastScrollTop = 0;

$(window).scroll(function() {
  const scrollTop = $(document).scrollTop();
  const scrollUp = scrollTop < lastScrollTop;

  lastScrollTop = scrollTop;

  if (scrollTop > navHeight && !scrollUp) {
    $scrollTopBtn.stop().fadeIn();
  } else if (scrollTop < navHeight && scrollUp) {
    $scrollTopBtn.stop().fadeOut();
  }
});

$(document).ready(() => {
  $('a[href*="#"]').on('click', function(event) {
    const hash = this.hash;
    
    if (this.hash) {
      event.preventDefault();

      $('html, body').animate({
        scrollTop: $(hash).offset().top - navHeight,
      }, 350);

      window.location.hash = this.hash;
    }
  });
});
body {
  margin: 0;
  font-family: monospace;
}

nav {
  position: sticky;
  top: 0;
  display: flex;
  background: white;
  border-bottom: 2px solid black;
}

a {
  height: 40px;
  display: flex; 
  align-items: center; 
  padding: 0 8px;
  border-right: 2px solid black;
}

.block {
  min-height: 100vh;
  border-bottom: 2px solid black;
  display: flex; 
  justify-content: center;
  padding: 32px 50vw 32px 32px;
  box-sizing: border-box;
}

#scroll-top-btn {
  position: fixed;
  right: 8px;
  bottom: 8px;
  width: 40px;
  height: 40px;
  border: 2px solid black;
  display: flex; 
  align-items: center;
  justify-content: center;
  padding: 0;
  background: white;
}
<nav>
  <a href="#block1">Block 1</a>
  <a href="#block2">Block 2</a>
  <a href="#block3">Block 3</a>
</nav>

<div id="block1" class="block">
  Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.
</div>

<div id="block2" class="block">
  Sed ut perspiciatis unde omnis iste natus error sit voluptatem accusantium doloremque laudantium, totam rem aperiam, eaque ipsa quae ab illo inventore veritatis et quasi architecto beatae vitae dicta sunt explicabo. Nemo enim ipsam voluptatem quia voluptas sit aspernatur aut odit aut fugit, sed quia consequuntur magni dolores eos qui ratione voluptatem sequi nesciunt. Neque porro quisquam est, qui dolorem ipsum quia dolor sit amet, consectetur, adipisci velit, sed quia non numquam eius modi tempora incidunt ut labore et dolore magnam aliquam quaerat voluptatem. Ut enim ad minima veniam, quis nostrum exercitationem ullam corporis suscipit laboriosam, nisi ut aliquid ex ea commodi consequatur? Quis autem vel eum iure reprehenderit qui in ea voluptate velit esse quam nihil molestiae consequatur, vel illum qui dolorem eum fugiat quo voluptas nulla pariatur?
</div>

<div id="block3" class="block">
  But I must explain to you how all this mistaken idea of denouncing pleasure and praising pain was born and I will give you a complete account of the system, and expound the actual teachings of the great explorer of the truth, the master-builder of human happiness. No one rejects, dislikes, or avoids pleasure itself, because it is pleasure, but because those who do not know how to pursue pleasure rationally encounter consequences that are extremely painful. Nor again is there anyone who loves or pursues or desires to obtain pain of itself, because it is pain, but because occasionally circumstances occur in which toil and pain can procure him some great pleasure. To take a trivial example, which of us ever undertakes laborious physical exercise, except to obtain some advantage from it? But who has any right to find fault with a man who chooses to enjoy a pleasure that has no annoying consequences, or one who avoids a pain that produces no resultant pleasure?
</div>

<button id="scroll-top-btn" style="display: none"></button>

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

Related