Personalized scrollbar extends beyond the screen

I have been working on creating my own scroll bar, and for the most part, it's functioning well. However, there is one small issue that I'm facing.

Whenever I reach the bottom of the page, the handle of the scroll bar disappears underneath the viewport.

Here is a GIF showing the problem:

I understand that this issue is related to CSS, but I am unsure about how to adjust it properly. The .full-height class in Foundation's .off-canvas-content adds a height property to prevent the scroll bar from being fixed to that element. The scroll bar markup is inserted into div.content, where all the remaining content resides.

I am aiming to ensure that the handle bar stops at the bottom of the container when the user has scrolled to the very end of the document, but I haven't found the correct method to achieve this yet.

CSS:

.scroll-container {
    position: fixed;
    right: 50px;
    top: 0;
    height: 100%;
    width: 7.5px;
    background-color: rgba(55,55,55,.3);
}

.scroll-bar {
    position: relative;
    top: 0;
    height: 20%;
    width: 100%;
    background-color: #6A1B9A;
}

.full-height {
    height: 100vh;
    min-height: 100vh;
}

.content {
    float: left;
    width: 100%;
    height: 100%;
    display: block;
    padding: 10px 20px;
    overflow-y: scroll;
}

JS:

(function($) {
    $.fn.scroller = function() {
        var self = this,
            scrollBarDrag = false,
            docHeight = $(document).height();

        var scrollContainer = document.createElement('div'),
            scrollBar       = document.createElement('div');

        scrollContainer.className = 'scroll-container';
        scrollBar.className = 'scroll-bar';

        scrollContainer.appendChild(scrollBar);

        self[0].appendChild(scrollContainer);

        self.on('scroll', function() {
            var top = $(this).scrollTop();
            setScrollBarTop(top);
        });

        function setScrollBarTop (top) {
            scrollBar.style.top = top + 'px';
        }
    };

})(jQuery);

I have experimented with various plugins for this issue, but they do not provide the exact functionality I need (such as missing mouse wheel click and drag to scroll), so I decided to create my own lightweight version. While suggestions about using plugins are welcome, I am currently focusing on finding a solution independently.

With absolute positioning:

Answer №1

Consider the height of the scrollbar in your calculations. For example, if the scrollbar is 100px tall and your page is 500px tall, you can only move it by 400px.

To adjust for this difference, determine the ratio between the scrollbar height and the document height, and use that to update the scrollbar position accordingly.

While I haven't tested it, a possible solution could look like this:

var availableHeight = totalDocumentHeight - scrollbarHeight;
var ratio = availableHeight / totalDocumentHeight;
function updateScrollBarPosition (position) {
    scrollbar.style.top = (position * ratio) + 'px';
}

Answer №2

After much trial and error, I have finally found a solution to this problem. It took some time, but I hope that my findings can benefit others as well.

I have made some revisions to the code for better clarity:

self.on('scroll', function() {
    elHeight = self.height();
    docHeight = $(document).height();

    var sTop = self[0].scrollTop;
    var sHeight = self[0].scrollHeight;
    var sBHeight = $(scrollBar).height();

    var ratio = (elHeight - $(scrollBar).height()) / elHeight;
    var currentPosY = (sTop / (sHeight - docHeight)) * 100;

    scrollBar.style.top = (currentPosY * ratio) + '%';
});

Answer №3

To calculate the scroll ratio, follow these steps:

1. Divide the height of the thumb by the height of the container and add 1.

2. Note that the containerHeight refers to the overflow: hidden container, not the scroll area's height.

3. When you obtain the scrollTop value, simply multiply it by the ratio obtained in step 1. For example:

thumbPosition.top = el.scrollTop * ratio + 'px';

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

The Gulp task is failing to generate the CSS file

Greetings! I have a task set up in my gulpfile.js as shown below: const gulp = require('gulp'); const sass = require('gulp-sass'); gulp.task('sass', function(){ return gulp.src('sass/*.scss') .pipe(sass()) ...

Using PHP with a form that allows multiple selections: in the case that the first task option is chosen, utilize the following code

HTML: <select name="taskOption[]" multiple> <option>first<br /></option> <option>second<br /></option> <option>third</ option> </select> PHP: <?php foreach ($_GET['taskOptio ...

Display the chosen alternative in a Bootstrap dropdown menu

I am currently facing an issue with the dropdown list in my bootstrap menu. <li class="dropdown"> <a aria-expanded="false" aria-haspopup="true" role="button" data-toggle="dropdown" class="dropdown-toggle" href="#">Chose option<span class="c ...

"Arranging elements with identical class in a single column but on separate rows using CSS grid - a step-by-step guide

I'm facing an issue with organizing choices and matches in columns using grid CSS. Currently, the match column is overlapping with the choice column. Here is how it is coded at the moment: .grid{ display:grid; grid-template-columns: 1fr 1 ...

jquery counter is malfunctioning

I noticed a strange issue with the counters on my website. They count up as expected when the page loads, but for some reason, when the screen width shrinks below 800px, they don't start automatically. However, if I quickly scroll to where the counter ...

Opera and Internet Explorer have trouble properly applying css text-decoration

It appears that the CSS text-decoration style is not being correctly displayed in Opera 11 and IE 9, but works perfectly fine in Chrome, Firefox, and Safari. Can anyone offer a solution to fix this issue? Incorrect Rendering: Correct Rendering: Below is ...

I want the navigation bar to appear only upon scrolling, but when I refresh the page it is already visible, and then vanishes as I start scrolling

I'm working on a project where I want the navigation bar to only appear after scrolling a certain distance down the page. However, I've noticed that when I refresh the browser, the navigation bar appears immediately and then disappears once I sta ...

Is there a way to add a disappearing large space that vanishes when a line break occurs?

I am currently working on a website where I aim to have the name and airport code displayed in a centered title above an image of the airport. The name and code will be separated by an em space: div.terminal-silhouette-container h3 { text-align: center ...

The $.parseJSON function accurately retrieves valid items but also presents an endless stream of undefined

Currently, I am in the process of developing a Flask application that fetches teams from a football league. The teams_list method returns the result of an AJAX request. While the output is correct, it seems to trigger an infinite loop that significantly sl ...

What is the best way to upload an object in React using fetch and form-data?

Currently, I am facing an issue where I need to send a file to my express app as the backend. The problem lies in the fact that my body is being sent as type application/json, but I actually want to send it as form-data so that I can later upload this file ...

I encountered difficulty clicking a button due to its unique button data-order-group-id while using python and selenium

Need help with javascript code for repeating orders: <div class="col-ea-1 repeat-order repeatable-order"> #common row in other snippets <button data-order-group-id="a9755447-04ff-4d00-59bf-06ff87f8ead6" #different row data- ...

Issue with searching in datatables functionality is not working

My datatable is not dynamically updating from the PHP script. The search functionality is not working with datatables when using sAjaxSource data. Can someone please provide a JSFiddle example without using sAjaxSource for search data? Additionally, pagina ...

Identifying if a variable is redirecting

Dealing with React Router Dom V6 I am facing an issue with two loader functions that make server requests. async function fetchUserDetails(userId, userAction) { const token = getAuthToken(); const userData = await axios({ url: API.endpoint + &apos ...

Transferring a Data array from JSON to a WCF function as a parameter

Hello everyone, I am utilizing JSON to transfer data in a WCF service. Below is the code snippet that shows how I am successfully passing data using ProjectCollection. However, my goal is to pass data as an array like this: var ProjectCollection = [&apos ...

Is there a way to achieve this without relying on Ext.getCmp in this particular code snippet?

I am currently using the following code to trigger a button click event once the window show event is called. It works perfectly fine, but I want to achieve the same functionality without using Ext.getCmp. Here is the line of code: Ext.getCmp('recen ...

Error: The value is null and cannot be read

My external application is set up within a const called setupRemote, where it starts with the appConfig in the variable allowAppInstance. export const setupRemote = () => { if (isRemoteAvailable) { try { ... const allowAppInstance = S ...

How can you fix the "bad value" response in mongodb when utilizing query parameters in the url?

{ "ok": 0, "code": 2, "codeName": "BadValue", "name": "MongoError" } Whenever I attempt to use query parameters skip and limit in the url, this error message pops up. localhost:5 ...

Slide down on the closest element with a specified class when clicked

I am currently working on a grid layout where each column contains an image, name, title, and a written description. Right now, the written descriptions (p.sub-team-description) are hidden using display:none; I am looking to add some animation so that wh ...

Encountering Err_Connection_Refused while working with MVC WebAPI 2 and AngularJS

Seeking guidance on WebAPI, AngularJS, and .NET Authentication, I am currently following a tutorial mentioned HERE. The tutorial is brief (~under 10 mins), but I encountered an error stating Failed to load resource: net::ERR_CONNECTION_REFUSED. Typically, ...

What is preventing me from setting a background image in Angular 13?

Trying a different approach based on advice from Stack Overflow, I attempted the following: <div [style.background-image]="'url(https://picsum.photos/200)'"></div> Unfortunately, this resulted in no effect and the image was ...