Applying the document height to window height ratio to create a scale ranging from 1 to 100

My goal is to create a scroll bar using two divs with heights of 110px and 10px. The smaller one will be nested inside the taller one, allowing for adjustment of its margin-height from 0 to 100px while still fitting within the larger div.

When I refer to fitting on a scale from 1 to 100 in the title, I am talking about setting the height of the smaller div.

Now, I am trying to determine how to calculate the ratio to position my 10px div relative to the taller div based on the document's height ratio to the window's height.

I have been experimenting all night without success. Below is some code I have used, although I am removing it to focus solely on new ideas. Your advice is appreciated.


var wheight = $(window).height();
var dheight = $(document).height();
document.getElementById("wheight").innerHTML=wheight;
document.getElementById("dheight").innerHTML=dheight;
document.getElementById("sidescrollbtn").style.marginTop = '70px';

http://jsfiddle.net/vinicius5581/2y63xnxa/4/

Answer №1

Converting a value to a percentage can be done effortlessly. Then adjusting that percentage to fit the size of a scrollbar is straightforward.

        var offset = $(window).scrollTop();
        $(window).scrollTop(offset + 20);  
        var wheight = $(window).height();
        var dheight = $(document).height();

        //Indeed, it's as simple as this.
        var percentualOffset = (offset / wheight) * 100;

        //Alternatively, you can use dheight. It depends on your specific scenario
        //var percentualOffset = (offset / dheight) * 100;

        $("#sidescrollbtn").css("top", percentualOffset);

To see a functioning example, visit http://jsfiddle.net/2y63xnxa/9/

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

Adjust padding for smaller devices in React using Material UI

In my grid layout, I have columns set to 3,6,3 and a spacing of 3 between them. On larger screens, the spacing between grids looks fine. However, as the screen size decreases, the spacing remains the same which is not visually appealing. What I am aiming ...

Where is the best place for the heavy lifting in Redux - reducer, action, container, or presentation component?

I've been exploring the concept of container/presentational component separation as explained in this article. However, I find myself a bit confused about where certain parts of my code should be placed. Consider a simple list of items. When an item ...

Tips for wrapping the content of a <span> element within a <td> element

Can someone help me figure out how to wrap the content of a <span> tag that is inside a <td>? The style I have applied doesn't seem to be working. Here's the code snippet: <td style="white-space:nowrap;border:1px solid black"> ...

Retrieving JSON formatted data from PHP using jQuery

If I use a $.post method in jQuery, how can I retrieve the response from PHP? $.post("sql/customer_save.php",{ what: "edit",customer_no: $customer_no}); I want PHP to send back a response. echo json_encode(array("customer_id"=>$customer_id,"customer_ ...

Learn how to dynamically show the chosen option from a dropdown menu in input text fields using AngularJS

html file: <select ng-model="shipping" ng-options="shipping.shipping for shipping in shipAddress"> <option value=''>--Select Address --</option> </select> <form name="shippingForm" class="form-horizontal" role="form" ...

What is the best way to position this grid container directly beneath the search box using absolute positioning?

<!DOCTYPE html> <html lang="tr"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Unique Starter</title> ...

Achieving vertical alignment of form controls with labels that wrap in a row using Bootstrap 4

I am facing an issue where input elements in a row with labels above them are causing alignment problems when the screen width is reduced. The longer labels wrap to the next line and push the input element down, increasing the overall height of the row: h ...

One way to organize data from my API is by sorting it based on two date conditions. If one of those conditions is missing, the data should be placed at the beginning of the list

I am facing a challenge with sorting the return from my API based on the StartDate. However, I need to implement a validation where if there is no FinalDate provided, the data should appear at the first index of the result. StartDate: "2004-06-04" ...

What is the fastest way to invoke the driver.quit() method in Selenium?

Is there a way to force close the browser immediately instead of waiting for it to complete loading before calling driver.quit()? ...

How can I resolve the vertical adjustment issue of Bootstrap 5 input group on mobile devices?

My current issue involves using Bootstrap 5.2.3 to create an input group that displays a set of spans with the ".input-group-text" class alongside inputs with the ".form-control" class. While this setup works well on a computer screen, it does not adjust c ...

Express server controller encountering premature return from locally executed async function

I have developed an API endpoint using Node/Express. I am trying to call a local function asynchronously within the controller function, but instead of receiving the expected asynchronous results, the called local function is returning undefined immediat ...

Integrating a Vue application with an OpenId provider using the OpenId Connect library

Currently, I am in the process of developing a Single Page Application with Vue on the client-side and Java Spring REST APIs on the backend. My goal is to add security measures using OpenId Connect, specifically with RapidIdentity as the provider. Unlike ...

What is the process for creating a register command using discord.js and MongoDB Atlas?

How can I save my Discord member data using a register command? Please provide assistance! bot.js client.on("message", msg => { if (msg.content === "!register, ign:<input from member>, level:<input from member>"){ ...

Dispatch is functioning properly, however the state remains unchanged

I'm currently developing an application that utilizes redux for state management. In a particular scenario, I need to update the state. Here is how my initial state and reducer function are set up: import { createSlice } from '@reduxjs/toolkit&a ...

What is the reason for encodeURIComponent not encoding single quotes or apostrophes?

Although the escape() function was deprecated and replaced by encodeURIComponent, there is an issue with encodeURIComponent as it doesn't encode the single quote/apostrophe character. This poses a problem when trying to escape apostrophes in someone&a ...

The Vuex mutation does not execute synchronously and does not resolve as a promise

My vuex mutation doesn't work synchronously as expected. Here is the code: mutations: { computeStatusData(state, status) { if (status.active !== true) { return } const started = new Date(status.startedAt); started.setHour ...

Invisibility of form data on new page - PHP and Javascript

I have a webpage with multiple hyperlinks. Each hyperlink should redirect the user to a new page with the URL sent as POST data. What I can do: 1. Open the new page successfully. The issue I'm facing: 1. On the new page, I cannot access the URL ...

Generate a vertical line that spans the entire length of the webpage in a vertical direction

Looking for a way to add vertical borders that span the entire webpage to some text? Check out this HTML snippet: <div id="vLine"> <h1>text</h1> </div> Here's the accompanying CSS: #vLine { height: 100%; width: 5 ...

The Step-by-Step Guide to Adding a Function Style to Wordpress

Typically I would use enqueue in this manner wp_enqueue_style( 'mystyle', get_stylesheet_directory_uri() . '/css/style.css',false,'1.1','all'); but now I have created a custom field and need to enqueue a style that ...

Developing an ASP application using the MVP pattern to return JSON data can be transformed into a S

I’m looking to incorporate the following code into a sails js Controller public JsonResult GetEvents() { //Using MyDatabaseEntities as our entity datacontext (refer to Step 4) using (MyDatabaseEntities dc = new MyDatabaseEntities()) { ...