Changing the position of the scroll bar in a side navigation bar using JS/jQuery

On my website, there is a side navigation bar with the following CSS style:

.scroll-box {
  overflow: hidden;
  width: 128px;
}
.filler {
  height: 256px;
  overflow-y: auto;
}
.selector {
  background-color: #369;
  padding: 8px 4px;
  text-align: center;
  flex-grow: 1;
  display: inline-block;
  cursor: pointer;
  box-sizing: border-box;
  transition: .1s !important;
}
.bar {
  height: 8px;
  width: 100%;
  background-color: #808080;
}
.label {
  padding: 4px 8px;
  background-color: #707070;
}
.active {
  background-color: lightgrey;
  color: #369;
}
<div class="scroll-box">
  <div class="label">Dates</div>
  <div class="filler">
    <div class="selector">4-Aug-16</div>
     ...
    
    <div class="selector active" id="today">15-Aug-16</div>
   ...
    <div class="selector">4-Aug-16</div>
</div>
  <div class="bar"></div>
</div>

I am looking for a way to automatically center the view of the side nav bar on the element with the today id without affecting the page scroll. I have experimented with using myUrl#today, but that changes the entire page's scroll position.

Is there a method to solely change the position of the side nav bar scroll to center on the #today element? Any suggestions on how this can be achieved would be greatly appreciated.

I am open to utilizing jQuery and JavaScript for this solution.

Thank you.

Answer №1

If you're looking to incorporate jQuery into your code, consider utilizing the following snippet:

$(document).ready(function(){
  // Ensure document is ready
  if($('#today').length > 0){
    var distance_to_top = $('#today').offset().top;
    var top_label_height = $('.label').height();
    var distance_to_scroll = distance_to_top - top_label_height - 8; 
    $('.filler').scrollTop(distance_to_scroll);
  }
});

This script finds the offset of the 'today' element in relation to its parent, adjusts for the label height, and scrolls to the top accordingly.

For a live demonstration, visit this link.

Answer №2

Perhaps this solution will work (I haven't had a chance to test it yet).

The idea is to iterate through each element within the specified div that does not have the id "today", summing up their heights along the way. Once we encounter the element with the id "today", we stop the iteration and set the scrollbar's height to match the total height of all preceding elements.

$(document).ready(function(){
    var height = 0;
    $(".filler *").each(function () {
        if($(this).is("#today"))
        {
            return false; //exit the loop
        }
        else
        {
            height += $(this).height();
        }
    })
    $("div.demo").scrollTop(height); //adjust the scrollbar's position
});

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

Generating a vertical bar adjacent to a bullet point in a list

Is there a way to add a vertical line next to each list item (except the last) without adding a new div? Adding a border line added an extra one that I didn't want. Sample HTML: <ul class="list"> <li><span id = "home">H ...

Tips on accessing the v-model value with a parameter in VUE

Looking to access the v-model value using a parameter, I attempted the following code: <template> <div v-for="(item, idx) in data"> <input :id="item" :v-model="item"></input> <button @click=&q ...

Encountering a problem with Selenium when dealing with tabular data displayed in a DIV format on a website, where each row is encapsulated within its own DIV element

While creating Selenium automation tests for a website with multiple rows contained within a main DIV element, each row represented by a separate DIV. For example, if there are 5 dynamically generated rows, the HTML code structure would look like this: < ...

Incorporating the latest version of SMINT into your Shopify store

Appreciate the help you're about to give. Here's the process of incorporating Smint v3.0 into Shopify: Added jquery.min.js and jquery.smint.js to asset files Inserted the following code within the tag of theme.liquid {{ 'jquery.mi ...

Position a form in the center of a container and showcase an additional div on the right with an indentation

My goal is to center a form within a div and have another div on the right that is slightly indented, but I'm struggling to align the elements properly. How can I achieve this layout using CSS? Additionally, is there a way to center the right-hand d ...

Error encountered: Index 109 - The function $.ajax(...).success is not recognized as a valid function while working with jQuery in a Node

I'm just starting to learn about jquery and have been experimenting with ajax in my recent code. Below is the snippet of what I have implemented: $(function(){ $("#status").change(function(){ if($(this).is(':checked')) ...

Problems encountered when trying to relocate an element to a higher position

Struggling to rearrange the order of the <h3 class="title"> and <span class="meta"> elements within this code block. It should work seamlessly across all instances on the page, not just one. <div class="col”> <a href="/3rd-news-post ...

Is there a way to display my <i> tags inline without any issues?

I am facing an issue with my code and need assistance. I have two links that I want to display but my code doesn't seem to respond as expected. The first link is: https://i.sstatic.net/fryPH.png The second link is: https://i.sstatic.net/j849M.png A ...

The dimensions on Next.js pages exceed those of the viewport by a significant margin

I have recently encountered a perplexing issue where the dimensions of my webpage appear to be 2.7 times larger than the viewport, even when there is no content or styles applied. The strange part is that it seems as though the page has been scaled up, eve ...

How many server queries does a single web application require?

As someone new to web app development, my main goal is to optimize speed as much as possible. I am faced with two options: The first option is to fetch data from the database individually every time a refresh is needed in the app. Alternatively, I c ...

Optimizing the Placement of Dynamic Google Maps

After setting up a responsive Google map using this jsFiddle and guidance from this stack overflow post, I encountered an issue. How can I keep the map centered on the marker across various viewports and browser sizes? I came across a solution in this res ...

JQuery class for swapping elements upon scrolling

I am currently working on a navigation bar that changes classes to create a fading effect for the background. The approach I have taken involves targeting the window itself and monitoring the scroll position of the user. If the user scrolls down more than ...

How can I access data entries in Firebase that have a particular key?

I've got some data stored in firebase with a structure like this: "application": { "companies": { "firebase": { "creation": { "name": "Firebase Inc", "location": "USA" }, "google": { "creattion": { ...

A guide on retrieving the selected option from a dropdown menu with React Material UI

Utilizing Material UI React, I am constructing a dropdown menu containing various options. My concern is: if I choose two options from different dropdowns within the menu, how can I intercept or store which option was selected? Below is a snippet of my co ...

What could be the reason for the malfunctioning of the where feature in Cloud Firestore?

Looking to create a warning system using discord.js and utilizing Cloud Firestore as the database. The goal is to have a system where when an admin triggers a command, it utilizes the where function to locate all documents containing the userid of the user ...

Creating a stunning full-screen background effect using HTML and CSS with the help

I'm currently designing a website with a full-screen background image. To ensure compatibility on all screen sizes, I've incorporated the jQuery Backstretch plugin. However, I've encountered an issue where the text embedded in the backgroun ...

Show rows in the table based on the child nodes retrieved from the backend database

I am facing a minor issue with a table Below is the table <table> <thead> <th>Name</th> <th ng-repeat="value in drilldownReport.columns"> {{ drilldownReport.columnNames[value] }} ...

What is the process for attaching a dynamically generated object to the document's readiness event?

One of my tasks involves dynamically generating a slider element using the code snippet below: function NewDiv(){ for (var count=0; count < parseFloat(sessvars.storey_count); count++) { var string="<br><div ...

Utilizing the closest method to set selection choices within a table's select tag

Currently, I am attempting to populate dynamic options in a select tag that is located within a table. The number of rows in this table can vary based on certain conditions. After retrieving the data via ajax, I am running into issues when trying to set i ...

Repeatedly iterates through the JSON properties that have been grouped together

https://jsfiddle.net/MauroBros/f1j0qepm/28/#&togetherjs=qedN5gf7SF Upon examining a JSON object, the structure is as follows: var values = [ {"aname":"account1", "pname":"pname1", "vname":"vname1& ...