Switch classes while navigating within a div

My website has a sticky sidebar with a list of cars and their corresponding categories in a table:

<ul class = "cars">
       <li class=""><a href="javascript:void(0)" class="model" data-id="1"> BMW </a></li>
    ......
        <li class=""><a href="javascript:void(0)" class="model" data-id="2"> Mercedes </a></li>
</ul>

The categories are represented as <div> elements like this:

<div class="element-title" id="car-category-1">BMW</div>
.....
     <div class="element-title" id="car-category-2">Mercedes</div>

My goal is to change the active class of the car in the list when scrolling through its corresponding category. Here's the jQuery code I'm using for this functionality:

$(document).on('click', '.model', function () {
    var this_id = $(this).data('id');
    var gotom = setInterval(function () {
        cars_go_to_navtab(this_id);
        clearInterval(gotom);
    }, 400);

    $('.cars li').removeClass('active');
    $(this).parent().addClass('active');
});
function cars_go_to_navtab(id) {
    var scrolling_div = $('#car-category-' + id);
    $('html, body').animate({
        scrollTop: scrolling_div.offset().top - 70
    }, 500);
}

Answer №1

Check out this informative article on CSS-Tricks for a pure CSS solution (although it may not be exactly what you need), which also references another excellent article that utilizes the Intersection Observer. To implement this in your code, consider adding something similar to the following:

const observer = new IntersectionObserver(entries =>
{
  for (const entry of entries) {
    if (entry.isIntersecting) {
      // add css style here
    }
    else {
      // remove css style here
  }
});
observer.observe(document.querySelector('#your-element-selector'));

Additionally, make sure to test compatibility across various browsers using a support table like canIuse.

Answer №2

A straightforward approach using JQuery. Additionally, investigate the potential of the Intersection Observer API

$(document).on("scroll", function() {
  var scrollPos = $(document).scrollTop();
  $('#menu a').each(function() {
    var currLink = $(this);
    var refElement = $(currLink.attr("href"));
    if (refElement.position().top <= scrollPos && refElement.position().top + refElement.height() > scrollPos) {
      $('#menu ul li a').removeClass("active");
      currLink.addClass("active");
    } else {
      currLink.removeClass("active");
    }
  });
});
* {
  margin: 0;
  padding: 0;
}

.container {
  display: flex;
  font-family: helvetica, sans-serif;
}

.content {
  flex: 1;
  padding-left: 200px;
}

.section {
  background-color: grey;
  height: 100vh;
  width: 100%;
  overflow: hidden;
  padding: 20px;
  box-sizing: border-box;
}

#menu {
  position: fixed;
  top: 0;
  background: #444;
  width: 200px;
}

#menu a {
  padding: 10px;
  display: flex;
  color: #FFF;
  text-decoration: none;
}

h1 {
  font-size: 30px;
  color: #FFF;
}

.active {
  background: #4CAF50;
  color: #FFF;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
<div class="container">
  <div id="menu">
    <ul>
      <li><a class="active" href="#bmw">BMW</a>
      </li>
      <li><a href="#mercedes">Mercedes</a></li>
    </ul>
  </div>
  <div class="content">
    <div class="section" id="bmw">
      <h1>
        BMW
      </h1>
    </div>
    <div class="section" id="mercedes">
      <h1>
        Mercedes
      </h1>
    </div>
  </div>
</div>

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

Tips for displaying a sub-menu upon hovering

I am attempting to display the list of sub-menu items when hovering over the main menu item. I have tried using the following CSS code, but it did not work as expected. Any assistance will be greatly appreciated. CSS: summary.header__menu-item.list-menu__ ...

Obtaining the source code from a different domain website with the help of jQuery

Is there a way to extract part of the source code from a YouTube page without using server-side programming? I've tried cross-domain AJAX techniques like Yahoo YQL and JsonP. While Yahoo YQL allows me to grab part of the source code, I'm facing ...

Preventing the occurrence of empty nested arrays within the state

I am currently working on a React Redux application where I am adding movies and including images as a nested array within my object. Here is what my state looks like after adding an item: { movies: [ { "title": "asda", "director": "as ...

Discover the method for creating URLs that are relative to the specific domain or server on which they are hosted

I need to adapt my menu bar to cater for different server environments: <a href="http://staging.subdomain.site.co.uk/search/page">Menu</a> The main source site is hosted on an external subdomain from an API service, and I want the URLs in my ...

Steps for configuring jQuery hide(), adding Class, and remove Class for flawless execution

My HTML Code is structured as follows : ... @foreach($hotel as $key=>$value) ... <div class="iteration"> <input type='hidden' value='<?php echo $value['HCode'].'#' ...

Clear input field after successful submission using jQuery

When the form is submitted correctly, I want to clear the input values. However, a problem arises - if the inputs are not filled in, they get erased. Any help would be greatly appreciated. Here's my code: $(document).ready(function(){ $("#Insert" ...

Is it necessary to include a request in the API route handler in Next.js when passing parameters?

In my API route handler, I have a function for handling GET requests: import { NextRequest, NextResponse } from "next/server"; export async function GET(req: NextRequest, { params }: { params: { id: string } }) { const { id } = params; try { ...

The AngularJS $HTTP loop counter fails to update

When working with an HTTP service and binding JSON data to HTML, I implemented the following code: This function uses a 2-second timer to automatically fetch data whenever there is a change in the backend. function sampleDevices ...

What is the most effective approach for preventing the inadvertent override of other bound functions on window.onresize?

As I delve deeper into JavaScript, I constantly find myself pondering various aspects of it. Take for instance the window.onresize event handler. If I were to use the following code: window.onresize = resize; function resize() { console.log("resize eve ...

Direct users according to their browser language (excluding php)

My site is going to have content in 3 languages, with French set as the default (fr). Here's how the structure of the website looks: Root directory (important note: no php files, just plain html) /fr/ Index.html About-us.html Contact.htm ...

Retrieve the id and value attributes of a checkbox using the success callback function in jQuery AJAX

I'm currently working on a web application project using JSP, jQuery, AJAX, MySQL, and Servlet. Within my project, I have a table.jsp file structured as follows: <form id="frm_table"> Username : <input type="text" id="txt_name" name= ...

Using two variables for iteration in Vue.js v-for loop

Can you create a v-for loop with two variables? I attempted the following, but it did not function as expected <ul id="example-1"> <li v-for="apple in apples" v-for="banana in bananas"> {{ apple .message }} {{ banana .message }} & ...

Is it possible to utilize the import feature to access and read a JSON file within a Next.js 13 API scenario?

Currently, in my Next.js 13 project, I am using the App Router feature to work with an API route that reads a file from a language folder within the resources directory. The code structure of this API is as follows: // app/api/file/[lang]/write/route.ts i ...

Determine distinct items in an array that match a predefined criteria

I have a list of objects with two keys, img1 and img2. I need to identify unique objects based on the values of img1, while also retaining the corresponding value of img2. This is the current code I am using: const imgs_arr = [ ...new Set( inpu ...

Utilizing AngularJS within a Captive Network Assistant (WISPr) on iOS and MacOS devices

In my past experiences with projects, it has been observed that Apple's Captive Network Assistant (also known as WISPr client) operates with a restricted browser. For further information, you can refer to How can I debug the browser in Captive Portal? ...

The height and alignment of the <a> tag and <p> element vary within a flex container

Currently, I am in the process of constructing a bottom navigation bar for a blog page. This navigation bar will allow users to easily navigate between the last blog entry, the main blog home/index, and the upcoming post. However, when the user reaches the ...

Adding images in ascending order according to the parent div's ID

If I have three different divs with unique IDs on a webpage <div id="product-id-001"></div> <div id="product-id-002"></div> <div id="product-id-003"></div> Is there a way to add image elements based on the ID of each d ...

Switching from real pixels to CSS pixels

The details provided in Mozilla's documentation on elementFromPoint clarify that the coordinates are specified in "CSS pixels" rather than physical pixels. This raises a question about what exactly CSS pixels entail. Many assume that a pixel in CSS is ...

What is the best way to conceal a canvas or another item?

Within my main canvas, there are three smaller canvases and a text element. <canvas id="Background" width="350" height="300" style="border:6px solid black; position: absolute; left: 10px; top: 10px;"> </canvas> <canvas id="Canvas1" width ...

Problem with MongoDB - increasing number of connections

I have encountered an issue with my current approach to connecting to MongoDB. The method I am using is outlined below: import { Db, MongoClient } from "mongodb"; let cachedConnection: { client: MongoClient; db: Db } | null = null; export asyn ...