Adjust the color of the sidebar's list items when scrolling

How can I change the background color of left sticky sidebars li on scrolling?
When scrolling through BMW, BMW's background color in the sidebar should turn green.
Please refer to the code snippet provided below.
The background color of the li elements should change similar to the click event but when scrolling.
Any assistance would be highly appreciated. Thank you.

var $ = jQuery;
$(document).on('click', '.car-category-link', function () {
    var this_id = $(this).data('id');
  
    var gotom = setInterval(function () {
        restaurant_go_to_navtab(this_id);
        clearInterval(gotom);
    }, 400);
   
    $('.car-list li').removeClass('active');
    $(this).parent().addClass('active');
});


function restaurant_go_to_navtab(id) {
    var scrolling_div = $('#car-category-' + id);
 
    $('html, body').animate({
        scrollTop: scrolling_div.offset().top
    }, 500);
}
<!DOCTYPE html>
<html>
<head>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<style>
body {
  margin: 0;
}
ul {
  list-style-type: none;
  margin: 0;
  padding: 0;
  width: 25%;
  background-color: #f1f1f1;
  position: fixed;
  height: 100%;
  overflow: auto;
}
li a {
  display: block;
  color: #000;
  padding: 8px 16px;
  text-decoration: none;
}
 .car-list .active {
  background-color: #4CAF50;
  color: white;
}
.table {
margin-left:25%;padding:1px 16px;height:1000px;
}
input {width:400px}
</style>
</head>
<body>

<ul class="car-list">
<li class="active"><a href="javascript:void(0)" class="car-category-link" data-id="0"> Honda </a></li>
<li class=""><a href="javascript:void(0)" class="car-category-link" data-id="1''>> BMW </a></li>
<li class=""><a href="javascript:void(0)" class="car-category-link" data-id="2"> Mercedes</a></li>
<li class=""><a href="javascript:void(0)" class="car-category-link" data-id="3"> Volvo </a></li>
<li class=""><a href="javascript:void(0)" class="car-category-link" data-id="4"> Main Course </a></li>
<li class=""><a href="javascript:void(0)" class="car-category-link" data-id="5"> Jeep </a></li>
<li class=""><a href="javascript:void(0)" class="car-category-link" data-id="6"> Buggati </a></li>
<li class=""><a href="javascript:void(0)" class="car-category-link" data-id="7"> Ferrari </a></li>
<li class=""><a href="javascript:void(0)" class="car-category-link" data-id="8"> Audi </a></li>
</ul>

<div class="table">
<div class="sticky-search" style="position: fixed; top: 50px;">
<input  placeholder="when the title is close to me then change li's background">
</div>
   <div class="element-title" id="car-category-0">
<h2 class="text-color">Honda</h2>
<span></span>
</div>
<p>Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It...

Answer №1

After encountering a category mismatch issue, I devised a solution. The first step is to correct the categories, ensuring that the selection aligns with the intended destination. For example, if "Volvo" was selected but redirected to "Mercedes," there is a clear discrepancy.

To address this, I implemented an event listener that triggers once the user completes scrolling. This function assesses which headlines are still within our viewport. Starting from the initial headline, each one is evaluated until the first visible headline is identified as the new active element. Please note that only headlines are considered for visibility calculations, not the main text. In some cases, although the main text may be visible, the active li will pertain to the subsequent headline. If adjustments are required, kindly inform me.

Subsequently, upon identifying the visible headline, the active class is assigned to the corresponding li element, which has unique IDs added for streamlined class application.

var $ = jQuery;
$(document).on('click', '.car-category-link', function () {
    var this_id = $(this).data('id');
  
    var gotom = setInterval(function () {
        restaurant_go_to_navtab(this_id);
        clearInterval(gotom);
    }, 400);
   
    $('.car-list li').removeClass('active');
    $(this).parent().addClass('active');
});
...

//Additional JavaScript and CSS code snippets available in the original content
...

I incorporated a scrolling script from this resource along with a valuable answer found here. Recognition and gratitude to both sources for their contributions.

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

Problem with BeautifulSoup table parsing

I've been trying to create a table with expenses, amounts, and actions, but I'm having trouble with the alignment. I attempted to adjust it by changing the width, but that didn't solve the issue. Can someone point out what I'm doing wro ...

Why is the reference of `this` pointing to `o` in this scenario (o.method)() rather than the global object?

Let's consider the scenario with an object: var o = { prop: 3, method: function() {return this.prop} } My expectation was that calling (o.method)() would result in undefined, but instead it returned 3, indicating that the reference of this ...

What is the best way to dynamically refresh only the images on a webpage using Java, without causing any disruption to the other content on the page?

Is there a way to dynamically update only the images on a page from our database using Java, without impacting the other content on the page? ...

What could be the reason for the inconsistent behavior of onClick, causing it to occasionally fail to display the associated

I just started using typescript 2 days ago, mainly to create a custom component for my streamlit app. I've made a navigation bar with a tab that can be clicked on the sidebar, but it's displaying some erratic behavior. Sometimes when I click on t ...

Error encountered when deploying the app to the live server: 500 Internal Server Issue

I am encountering an issue with my ASP.Net web app's ajax file upload feature. While it works perfectly on my local host machine during testing, I face a 500 Internal Server error when I try to publish it to a website. The console output in Google Chr ...

Unable to retrieve class object in PHP file loaded from AJAX request

I have encountered a minor issue with the following setup and I am seeking assistance to enhance my knowledge for future projects. Current Setup: There is a user class in PHP located within the models directory. A file named home.php is present in the r ...

Investigating the issue of jQuery autocomplete combobox line items breaking in all versions of Internet Explorer. Let's dive into this matter

Having an autocomplete combobox within a div that expands into a dialog box presents visual issues in Internet Explorer. The line items are tightly packed together and the text is not fully visible. To replicate this error, you can obtain the source code d ...

Special effects for the images动画效果。

Is there a way to add animation effects to images in the about section using this code: <div id="about" class="row section bgimg3"> <div class="col-sm-8"> <h2 style="color:black;">Want to Know More About me?</h2> ...

How to divide an HTML string into an array using PHP

I am in need of some assistance from you all. The issue I am facing involves dealing with a string of HTML that looks like this: <h4>Some title here</h4> <p>Lorem ipsum dolor</p> (some other HTML here) <h4>Some other title ...

Determining the Height of a Navigation Bar Automatically with CSS

My website is built using React and react-strap. I set up my .header-overlay to cover the entire background within the .header. However, due to the presence of the .navbar, the .header-overlay extends beyond the boundaries of the .header vertically. I tho ...

Tips for positioning a navigation bar in the center for various screen resolutions

After hours of searching, I still can't find a solution to my problem. I'm new to this, and on my main monitor, everything looks centered just fine. 1920x1080: View larger image But on my 1280x1024 monitor: View smaller image As you can see, i ...

Update the second dropdown automatically based on the selection in the first dropdown menu

I need assistance with creating two dropdown menus that are linked, so when an option is selected in the first menu, it automatically changes the options available in the second menu. Both menus should be visible at all times. I have set up a fiddle to pr ...

Steps to dynamically set the value of an input type="time" using JavaScript

Despite the repetitive nature of these questions, I have yet to find a solution to my specific query. Any help would be greatly appreciated. Thank you in advance. The HTML code is as follows: var start="10:30 PM"; $scope.edit={} frtime=start.split("PM ...

Failed to build development environment: Unable to assign the attribute 'fileSystem' to a null value

I'm attempting to launch an Ionic 2 Application, but I keep encountering this error when running ionic serve Error - build dev failed: Unable to assign a value to the 'fileSystem' property of object null Here is the complete log: λ ion ...

The removal of a JQuery element can result in causing the webpage to become unresponsive and lead to

When attempting to create a loop in JQuery to remove elements from my HTML, I encountered an issue where the function caused my browser to hang and become unresponsive. Here is the JQuery code I used: function removeElement(){ var i =0; ...

Having trouble with your GitHub Pages site displaying properly on desktop but working fine on mobile?

I am facing an issue with my GitHub pages site on a custom domain. It works perfectly fine on mobile, but when I try to access the same URL from desktop, I encounter a DNS_PROBE_FINISHED_NXDOMAIN error. Any suggestions on why this might be happening? You c ...

Error: Cannot access collection property of dbObject

I've been working on fetching data from a database, but I've hit a roadblock. I keep encountering an error and can't seem to figure out what's causing it. I've searched for solutions but haven't found one that works yet. I&apo ...

As a Java developer, I am currently facing challenges with mastering jQuery

Hi everyone, I am completely new to jQuery and have just started using the auto complete feature. I would like to make it so that when I click on an item provided by the auto complete, the page automatically submits to another page. Here is the code I a ...

Sending handlebars variable to the client-side JavaScript file

I am currently working on an application using node.js along with express and handlebars, and I'm trying to find a way to transfer handlebars data from the server to client-side JavaScript files. Here is an example: //server.js var person = { na ...

Display two examples from the material-ui documentation

My goal is to merge two demos found in the material-ui documentation. Clipped under the app bar - Describes a page layout Fixed header - Illustrates a table with a fixed header. I am looking for a solution where the table occupies the entire available p ...