Tips for placing a scroll-to-top button on a webpage

How can I ensure that the gotop stays within the confines of the story - specifically at the bottom right of the middle div, while maintaining its show/hide functionality? The dimensions of the three divs - top, story and footer - are not fixed. I have experimented with various positioning and margin parameters without success.

$(document).on('scroll', function(){
let x = $(this).scrollTop();
if(x > 25){$('.gotop').show();}
else{$('.gotop').hide()}
});

$('.gotop').on('click', function(){
  $(document).scrollTop(0);
});
.container{
width:50%;
margin:0 auto;
background:silver;
text-align:center;
}
.top{padding:25px; background:gold;}
.story{
position:relative;
padding:25px;
min-height:100vh;
}
.footer{padding:25px; background:gold;}

.gotop{
display:none;
position:fixed;
z-index:99;
right:14px;
bottom:0;
cursor:pointer;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class='container'>
<div class='top'>TOP</div>
<div class='story'><br><br><br><br>STORY<br><br><br>
<div class='gotop'>gotop</div>
</div>
<div class='footer'>FOOTER</div>
</div>

Answer №1

Implement sticky positioning:

$(document).on('scroll', function() {
  let x = $(this).scrollTop();
  if (x > 25) {
    $('.gotop').show();
  } else {
    $('.gotop').hide()
  }
});

$('.gotop').on('click', function() {
  $(document).scrollTop(0);
});
.container {
  width: 50%;
  margin: 0 auto;
  background: silver;
  text-align: center;
}

.top {
  padding: 25px;
  background: gold;
}

.story {
  position: relative;
  padding: 25px;
  min-height: 150vh;
  /* Using flexbox to align the button at the bottom */
  display:flex;
  flex-direction:column;
}

.footer {
  padding: 25px;
  background: gold;
}

.gotop {
  display: none;
  position: sticky;
  margin-top:auto; /* Push element to the bottom */
  text-align:right; /* Align to the right */
  z-index: 99;
  right: 14px;
  bottom: 14px;
  cursor: pointer;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class='container'>
  <div class='top'>TOP</div>
  <div class='story'><br><br><br><br>STORY<br><br><br>
    <div class='gotop'>gotop</div>
  </div>
  <div class='footer'>FOOTER</div>
</div>

Answer №2

In this particular code snippet, I have made some adjustments by updating minor CSS styles and swapping out jQuery with vanilla JavaScript to incorporate the Intersection Observer. This change ensures that the visibility of the gotop element is tied to the appearance of the footer. While it is possible to use both jQuery and JavaScript concurrently, my preference was to stick with JavaScript due to my lack of experience with the former technology.

One key advantage of this modification is that it eliminates the need for hardcoded values to manage the visibility of the gotop component.

let footer = document.querySelector('.footer');
let gotop = document.querySelector('.gotop');

let observer = new IntersectionObserver((entries)=>{
entries.forEach(entry=>{
if(entry.isIntersecting){
 gotop.style.opacity = '1';
 gotop.style.pointerEvents = 'auto';
}
else{
 gotop.style.opacity = '0';
 gotop.style.pointerEvents = 'none';
}
})
})

observer.observe(footer);

gotop.addEventListener('click',()=>window.scrollTo({top:true}));
.container{
width:50%;
margin:0 auto;
background:silver;
text-align:center;
}
.top{padding:25px; background:gold;}
.story{
position:relative;
padding:25px;
min-height:100vh;
}
.footer{padding:25px; background:gold;}

.gotop{
opacity:0;
pointer-events:none;
position:absolute;
z-index:99;
right:14px;
bottom:0;
cursor:pointer;
transition:all 0.2s ease-in;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class='container'>
<div class='top'>TOP</div>
<div class='story'><br><br><br><br>STORY<br><br><br>
<div class='gotop'>gotop</div>
</div>
<div class='footer'>FOOTER</div>
</div>

Answer №3

To make the necessary adjustment, simply replace position:fixed; with position:absolute; in your .gotop div. This change is required because the div is positioned within a container with position:relative, which confines its placement.

$(document).on('scroll', function(){
let x = $(this).scrollTop();
if(x > 25){$('.gotop').show();}
else{$('.gotop').hide()}
});

$('.gotop').on('click', function(){
  $(document).scrollTop(0);
});
.container{
width:50%;
margin:0 auto;
background:silver;
text-align:center;
}
.top{padding:25px; background:gold;}
.story{
position:relative;
padding:25px;
min-height:100vh;
}
.footer{padding:25px; background:gold;}

.gotop{
display:none;
position:absolute;
z-index:99;
right:14px;
bottom:0;
cursor:pointer;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class='container'>
<div class='top'>TOP</div>
<div class='story'><br><br><br><br>STORY<br><br><br>
<div class='gotop'>gotop</div>
</div>
<div class='footer'>FOOTER</div>
</div>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Tips for customizing and removing single entries in a CRUD application

I am currently working on developing a CRUD app, but I am facing challenges in editing and deleting individual items. In my implementation, I have two <a> tags within a <span> tag for each created item - one for editing and one for deletion. Ho ...

Utilizing htmx for interactive elements throughout the website

When I make an htmx-request on my page, a loading spinner is displayed like this: <div class="col-4 px-4dot5 py-3 bg-secondary-light"> <label for="stellenangebotLink" class="form-label fs-5">Link</label> ...

Eliminating border on image map area

Is it possible to eliminate the outline that appears when selecting an area on an image map? Reference: I am currently using Chrome on Snow Leopard. ...

Develop a fresh AngularJS directive that utilizes the HTML5 audio element

Recently delved into Angular and managed to create audio buttons using an Angular directive: app.directive('soundButton', [function () { return { restrict: 'E', link: function (scope, element, attrs) { v ...

How should attributes be passed to the li element properly?

I am trying to transfer values from the database to the <li> tag. Can someone confirm if the approach below is valid and the proper way to do it? <li id='$current_row["RA_SUB_ID"]' component_name='$current_row["RA_SUB_NAME"]' ...

What is the best way to retrieve the current date and time in PHP?

How do I get the date and time similar to 05-17-05 at 02:33:15 Can you please assist me in writing this in php? Can I use at with the date function in php? ...

My CSS is giving me some trouble

Currently, I have 4 widgets with different sizes placed within a main div called #box. To center them, I reduced the width to about 60% and set margin left and right to auto. However, when I zoom out in my browser, the widget blocks move more to the left a ...

When attempting to click on my subtopics using jQuery, they do not appear as expected

$(document).ready(function () { $("#subTopics").hide(); $("#mainTopics").click(function () { $("#subTopics").show("slow"); }); }); body { margin: 0; } li, a{ text-decoration: none; list-style-type: none; text-d ...

Optimize your website by caching static pages and content using Node.js

When it comes to caching static content using nodejs, there seem to be two main methods that can be utilized: The first method involves using nodejs and utilizing the following code: app.use(express.static(path.join(__dirname, 'public'), { max ...

The table is not being queried for alphabet letters

I'm having an issue with my table that has a column called BarcodeID. The numerical values work fine and I get the correct output, but when it comes to alphabet letters, it's not working as expected. I keep getting an error message: Unknown co ...

Ensuring Your IMG is Perfectly Centered in DIV Across all Browsers

I have tried all the tips from the top Google results, but I am still struggling to center an image within a div. For example, the popular tricks mentioned in this link: or http://www.w3.org/Style/Examples/007/center.en.html do not seem to work in IE 8. ...

Place the emoji where the cursor is located

My query was already posted on stack overflow but unfortunately, I did not receive a response. The issue revolves around 2 links named "add emoji 1" and "add emoji 2". As mentioned earlier, my question can be accessed here: Insert smiley at cursor positio ...

PHP Lightweight HTML Content Scraper

I have been experimenting with a basic web crawler and here is the simple HTML code I used for learning purposes: input.php <ul id="nav"> <li> <a href="www.google.com">Google</a> <ul> <li&g ...

Design a floating text box similar to Gmail's style by incorporating Google's Material Design Lite

I have been utilizing the Material design lite library in an attempt to replicate the Floating text box feature seen in Gmail by Google. Despite not finding any official documentation on this particular component, I decided to experiment with the following ...

Utilize AJAX to showcase JSON data retrieved from a specified URL

We are striving to showcase the names listed in our JSON file within a div using JavaScript. Despite multiple attempts, we have not yet achieved success. JSON data: This is the approach we took: <button>fetch data</button> <div id="result ...

Footer remains fixed at the bottom, extends below the page

Looking for a way to keep the footer at the bottom of the page and automatically center the content between the header and footer. I have tried following this technique: However, my footer ends up appearing too far below, creating a large gap between sec ...

What is the best way to create a dynamic menu icon using CSS?

I am currently developing a CSS animation that is inspired by this. I have made progress and almost reached my goal, but I am facing some difficulties in getting it to work perfectly. For those unable or unwilling to visit the links: I aim to create an ani ...

The flexibility of the flex-wrap property does not extend to affect nested elements

Check out this example first: http://jsfiddle.net/8ofrs0y7/14/ <div class="flex-group"> <ul class="flex-container red"> <li class="flex-item"&g;1</li> <li class=&qu ...

Staggering CSS animation rendering techniques

I have put together a rotating border around a button on this CodePen, and while the concept seems promising, it's not functioning properly - the rendering performance is extremely slow and choppy (I'm using the M1 MacBook Pro). .button { wi ...

Animate as you scroll down and as you scroll back up

Trying to animate a set of buttons from a relative position to a fixed position on each scroll by. HTML <div class="menu"> <button class="button"></button> <button class="button"></button> </div> CSS .button ...