Tips for adding a progress bar to your sidebar

I have a query regarding how to expand the width of a div within an li element.

Essentially, as a user scrolls, the sidebar on the right-hand side will cause the span element (highlighted with a red background color) inside the li to transition from 0 to 100. To put it simply, when the first corresponding div comes into view, the span elements in the respective li items will adjust their widths from 0 to 100% based on the user's scrolling direction. This effect serves as an indicator of how much of the div has been scrolled by the user.

I have created a code pen example that demonstrates the desired functionality https://codepen.io/hellouniverse/pen/xdVJQp

Here is a snippet of my CSS:

.sidebar {
position: fixed;
max-width: 300px;

&__list {
    position: relative;
    text-align: center;
    padding: 10px;
    margin: 10px auto;
    border: 2px solid #f3f2f0;
    list-style-type: none;
    display: inline-flex;
    flex-direction: column;
}

// The primary red bar at the bottom that increases in width with scroll
span {
    background-color: red;
    height: 5px;
}

The issue lies within the javascript portion: I believe 1. We need to determine the height of the associated div 2. Adjust the span's width by a specific percentage based on the calculated height mentioned in step 1.

I am struggling to write the necessary code. Could someone provide assistance?

// Checks if an element is visible within the window
function isScrolledIntoView(elem) {
    'use strict';
    if (elem.length > 0) {
        var docViewTop = jQuery(window).scrollTop();
        var docViewBottom = docViewTop + jQuery(window).height();
        var elemTop = jQuery(elem).offset().top;
        return ((elemTop <= docViewBottom) && (elemTop >= docViewTop));
    }
}

var lastScrollTop = 0;

$(window).scroll(function() {

    // Adjusting the span's width within the li as you scroll

        var height = $('section-just-in').height();
        var incrementBy = 300 / height;


        $('.sidebar__list span').animate({
            // Increase width from 0 to 100%
            width : width + incrementBy
        });

})

Answer №1

Here are some resources to help you:

Check out this example on CodePen

Explore a similar demo on jsfiddle:

View it on jsfiddle

First step is to determine the height of each section

Second, monitor the scroll progress for every section

Lastly, implement the progress bar on each button accordingly.

$(document).ready(function() {
  var theone = $('#section-just-in');
  var thetwo = $('#videos');
  var thethree = $('#aboutteam');
  var theone_h, thetwo_h, thethree_h;

  theone_h = theone.innerHeight();
  thetwo_h = thetwo.innerHeight();
    // removing window height due to scrolling concerns
  thethree_h = thethree.innerHeight() - $(window).height();

  $(document).scroll(function() {
    var page_height = $("body").scrollTop();

    var pos_2 = page_height > theone_h ? page_height - theone_h : 0;
    var pos_3 = page_height > (thetwo_h+theone_h) ? (page_height - (+thetwo_h + +theone_h)) : 0;
    var progress_1 = (page_height / theone_h) >= 1 ? 100 : (page_height / theone_h) * 100;
    var progress_2 = (pos_2 / thetwo_h) >= 1 ? 100 : (pos_2 / thetwo_h) * 100;
    var progress_3 = ((pos_3) / thethree_h) >= 1 ? 100 : ((pos_3) / thethree_h) * 100;

    $("ul li:nth-child(1) span").stop().animate({
      "width": progress_1 + '%'
    }, 0);
    $("ul li:nth-child(2) span").stop().animate({
      "width": progress_2 + '%'
    }, 0);
    $("ul li:nth-child(3) span").stop().animate({
      "width": progress_3 + '%'
    }, 0);
  });




  // Checks whether an elem gets into view of the window
  function isScrolledIntoView(elem) {
    'use strict';
    if (elem.length > 0) {
      var docViewTop = jQuery(window).scrollTop();
      var docViewBottom = docViewTop + jQuery(window).height();
      var elemTop = jQuery(elem).offset().top;
      return ((elemTop <= docViewBottom) && (elemTop >= docViewTop));
    }
  }
});

Answer №2

Here is the solution:

let elementHeight,
    scrollIncrement,
    totalVisibleHeight;

$(document).ready(function(){
    totalVisibleHeight = $('.section-just-in').innerHeight(); 
});

$(document).scroll(function() {
    let scrollTopValue = Math.max( $("html").scrollTop(), $("body").scrollTop());

    scrollIncrement = (100 * scrollTopValue) / totalVisibleHeight / 1.4;

    $('.sidebar__list span').stop().animate({
        "width" : scrollIncrement
    });
});

To make it work, simply replace everything after the isScrolledIntoView function.

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

Deactivate hover effect on specific row in Bootstrap hover table

After searching for a solution, I came across this query. However, it did not provide the answer I was looking for. It suggested setting fixed backgrounds on specific rows, but this could potentially disrupt the style if, for example, a bg-gradient is set ...

Assistance needed with Angular 2 form for integrating backend features

Attempting to develop backend functions for a form within an Angular 2 project. While I successfully completed the front end portion, I am encountering difficulties with the backend implementation. The goal is to input data into the fields and upon hitting ...

Using the selector gadget to scrape websites with R programming

Attempting to extract information from the site: Encountered a few obstacles: Initially used the selector gadget to identify tables, but it was not effective. Simply typing "table" highlighted 9 tables. Upon running the following code: html <- read_h ...

JQUERY: The script in my dialog box seems to be stuck in a never

I'm encountering a peculiar issue. I have a dialog that includes an Add button, and after inputting text, another add button appears. The problem arises when I enter a second comment - it goes through the loop twice, and similarly with a third comment ...

Tips for dynamically loading fresh Google Adsense code with JavaScript without any user interaction

Recently, Google made a change in their ad code by replacing <script async src="https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js</script> with <script async src="https://pagead2.googlesyndication.com/pagead/js/adsbygo ...

Looking to toggle visibility on multiple divs with an onclick button in Jquery?

Lately, I've been struggling to make my code display questions in a specific order. My goal is to have the next question show up once the submit button is pressed, while hiding the previous one. Currently, I'm developing a game similar to Family ...

Improper headings can prevent Chrome from continuously playing HTML5 audio

Recently, I encountered a peculiar and unlikely issue. I created a custom python server using SimpleHTTPServer, where I had to set my own headers. This server was used to serve .wav files, but I faced an unusual problem. While the files would play in an ...

Looking to add a glowing effect to a div when hovered using jQuery

Seeking assistance to add a glow effect to a div when hovered using jQuery. Below is the code snippet: HTML <div class="tablerow"> <div class="image"> <img src="1.jpg"> </div> <div class="info"> ...

Variables defined within a React useEffect are not accessible outside of the function

I'm facing a scope issue where I need to declare a constant variable inside the useEffect hook in React, but the variable is not recognized outside the function. import React, { useEffect } from "react"; function Commentsbox(props) { useEffect(( ...

When you scroll down, the image and text will appear above the fixed header

As a newcomer to HTML and CSS, I've been working on creating an eCommerce page. The header is fixed, but I've encountered an issue where the image overflows on it when scrolling down the page. If my approach seems odd or unconventional, I would a ...

Displaying the blog post title in the metadata information

Currently, I am facing a challenge with my Jekyll site's Search Engine Optimization because I am having difficulty setting meta information. ... <meta name="og:title" content="{{ seo_title }}" /> ... <!-- now in my for post-loop: --> {% f ...

Guide on developing a regular expression to verify an identification number containing either three dots or dashes

users should only be allowed to enter IDs in the format shown below 1 1.1 or 1-1 1.1.1 or 1-1-1 1.1.1.1 or 1-1-1-1 I came up with this regex pattern: /^(\d+(?:-\d+)*$)|(^\d+(?:\.\d+)*$)/ The current output allows an unlimit ...

Jquery tooltip with a twist of a dropdown menu functionality

As I work on developing a jQuery plugin for displaying tooltips, I am interested in incorporating a feature where the tooltip can also function as a dropdown menu. This would allow users to click on links within the tooltip itself. However, I have encounte ...

Switch up Google Fusion URL using Jquery

Looking to modify Google Fusion query using jQuery, here is the code snippet: var fusionid= ""; function initMap() { var map = new google.maps.Map(document.getElementById('map-canvas'), { center: {lat: 28.3268, lng: 84.1855}, zoom: 7 } ...

Customized CSS scrollbar within a specific div

Is it possible to apply CSS to customize the scroll bar of a specific div without affecting the entire page layout? ...

JavaScript: Simply returning an array with no elements

As I work on refining a solution for fizzbuzz to generate an array of numbers and strings, I encountered an issue where the return statement only outputs an empty array. Interestingly, when I print the array to the console, it appears as intended with all ...

Can you explain the process of variable allocation?

I have a query regarding the following JavaScript code snippet. It might be a basic question, but I'm seeking clarification. // 'response' contains JSON data received from the backend: ....then(response => { this.myVar = response.data; ...

Steps for showing personalized validation error messages in Angular 7

Is there a way to highlight the input field of a form with a red border and display the message Password is invalid when a user types in a password that does not match the set password? I have managed to see the red border indicating an error when I enter ...

Is there a way to modify CSS class names on-the-fly within an Angular project?

I am working with two CSS classes named as below: .icon_heart{ color: #bdbdbd; } .icon_heart_red{ color: #a6b7d4;; } Within my HTML code, I have incorporated a heart icon. <div class="icon_heart" *ngIf="showheartIcon"> ...

ES6 scoping confusion: unraveling the mystery

I stumbled upon these two syntax methods for exporting functions. Let's say we have files named actions.js and app.js. The first method looks like this: in actions.js export function addTodo() {} export function deleteTodo() {} and in app.js I have ...