Skip to content

Scroll up for each article

I have a list of articles on my page, and starting with the second article there should be a scroll up button. The question is how to do it correctly. Here is my code

php.blade

<div class="blog-list">
    @foreach($articles as $article)
        <div class="blog-article @foreach ($article->blog_categories as $blog_category) category_{{ $blog_category->id }} @endforeach">
            <picture>
                <source srcset="{{ $article->main_image }}">
                <img class="article_image" srcset="{{ $article->main_image }}" alt="">
            </picture>

            <div class="container">

                //Scroll up
                <div class="top-button-blog-wrapper">
                    <div id="scrollTopButtonBlog" class="top-button-blog">
                        <div class="top-button-blog_text">To top</div>
                    </div>
                </div>

           <h2 class="blog-article__title">{{ $article->title }}</h2>
           <span>{{ date('d F Y', strtotime($article->published_at)) }}</span>

        </div>
    </div>
    @endforeach
</div>

js

//Scroll up
const scrollTopButtonBlog = document.getElementById('scrollTopButtonBlog');
scrollTopButtonBlog.addEventListener('click', () => {
  window.scrollTo({
    top: 0,
    behavior: 'smooth',
  });
});

Now my code adds a scroll button for each new blog, but it works only for the first one, maybe this Scroll up code should not be added to the article itself, but separately and simply fixed in the right place? What is the best way to proceed here?

Answer

Here’s an example of how I would do it

const scrollTopButton = document.getElementById("scrollTopButton");
document.addEventListener('scroll', function(e) {
  if(window.scrollY > 100) {
    // Removing inline style to reset the display property to what's set in stylesheet
    scrollTopButton.style.opacity = "1";
  } else {
    // Hiding the button with inline style
    scrollTopButton.style.opacity = "0";
  }
});
scrollTopButton.addEventListener("click", () => {
  window.scrollTo({
    top: 0,
    behavior: 'smooth',
  });
});
#scrollable {
  overflow:auto;
}
#firstDiv {
  background-color: green;
  height: 1500px;
}
#scrollTopButton {
  transition: opacity 0.5s;
  cursor: pointer;
  width: 100px;
  height: 15px;
  display: flex;
  align-items: center;
  justify-content: center;
  background-color: red;
  padding: 5px;
  position: fixed;
  bottom: 5px;
  left: 15px;
}
<div id="scrollable">
  <div id="firstDiv"></div>
  <div id="scrollTopButton" style="opacity: 0">ScrollTop</div>
</div>

As you can see, with an event listener on the scroll, you can know when the user scroll and how many pixel have been scroll by now. And in function of this, you can show/hide the button