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

Sync issues observed with jQuery slide animations

I am currently utilizing a carousel slider that includes text content. When the user clicks on the 'next' button, the .carousel-text div slides up to hide the text, the carousel then moves to the next slide, and finally the .carousel-text on the ...

The JQuery $post() function appears to be unresponsive

I have a HTML/JavaScript frontend and a PHP backend. I am trying to transmit a JSON string array from my frontend to backend using AJAX, but it is not working as expected. The code snippet below shows the implementation that is causing issues: <html> ...

It appears as though the promise will never come to fruition

I am currently developing an application that is designed to search for subdomains related to a specific domain and store them in a database. The application retrieves data from crt.sh and threatcrowd. One of the functions within the application parses th ...

What is the best way to prevent useEffect from triggering when a modal is being rendered?

I'm currently developing a react movie application. I am facing an issue with the hero picture feature that displays a random popular movie or show. Whenever I click the button to open a modal, the useEffect function is triggered and changes the movie ...

Looking to add a close button to the iFrame, but having trouble getting it to function when clicked

In my project built with Meteor, I have integrated an iframe to display specific content to the user. The iframe is functioning as expected, but I am looking to add a close button that will effectively unload the iframe when clicked. I attempted to imple ...

Connections between Wordpress websites and CSS styling

My inquiry consists of three parts: I am currently in the process of constructing a portfolio website using Wordpress, and I have encountered some peculiar links. For instance, on my about page, the link appears as localhost/AFolder/anotherfolder/ind ...

Combine an array of objects into a regular object

Imagine having an array structure as shown below: const student = [ { firstName: 'Partho', Lastname: 'Das' }, { firstName: 'Bapon', Lastname: 'Sarkar' } ]; const profile = [ { education: 'SWE', profe ...

Instructions on opening a modal and changing the source of the iframe within the modal

I currently have a modal within my application that is triggered by Bootstrap: <div class="modal full-page fade" tabindex="-1" role="dialog" id="fullpageModal"> <div class="full-page-content"> <button type="button" class="close" d ...

Error encountered in Typescript when attempting to invoke axios - the call lacks a suitable overload

When I make a call to axios, I include a config object like this: const req = { method, url, timeout: 300000, headers: { 'Content-Type': 'application/json' } } axios(req) An error in TypeScript is thrown stating that "No overload matc ...

Combining two arrays filled with objects to form a collection of Objects on a Map

In my JavaScript code, I'm receiving data from a WebService that looks like this: { "fire": { "totalOccurence": 2, "statsByCustomer": [ { "idCustomer": 1, "occurence": 1 }, { "idCustomer": 2, ...

Having trouble getting npm install to add any libraries? Wondering how to fix this issue?

Currently, I am using Node version 14.15.5, npm version 6.14.11, and working on VS Code. I attempted to install two packages with the following commands: npm install express npm install lodash Unfortunately, neither installation was successful. This ...

The art of combining CSS3 gradients with background images

I've created a function that changes the parent element's background gradient when a checkbox's status is toggled. Check out the Lorem link to see it in action! Click here to view. However, I've encountered an issue with applying this ...

"Utilizing Angular's $http.post to extract data from resolved promises

Can you help me figure out how to successfully send data through $http.post that I receive from a function using $q.defer()? Here is the code snippet: HTML <input type='text' ng-model='name'/> <input type='file' id= ...

Configuring Firefox settings in Nightwatch

Is there a way to set Firefox preferences in nightwatch? I am trying to achieve the same thing in Java using nightwatch. To set Firefox preferences in nightwatch, you can use the following code snippet: FirefoxProfile profile = new FirefoxProfile(); prof ...

The Axios.catch method does not handle network or console errors

Utilizing React with axios and redux-promise poses a challenge when it comes to handling 404 errors. See the example below: This is the snippet of code causing the issue: const url = FIVE_DAY_FORECAST_URL.replace("{0}", city); axios.interceptors.resp ...

Utilize Bootstrap to combine two tables within a single column efficiently

I am facing an issue with my layout that involves organizing 3 tables in a specific way. Two smaller tables are supposed to take up 3 bootstrap columns on the left side, while one larger table should occupy 9 columns on the right side. However, when I impl ...

Troubleshooting: Why isn't my CSS fixed position working for my sticky

I have a simple jQuery code snippet that is supposed to make the navigation element sticky by applying a class with position: fixed. However, I'm facing an issue on my Commerce platform where the fixed position property doesn't seem to work corre ...

Bootstrap component malfunctioning and not performing as expected

Currently, I am learning how to use Bootstrap and attempting to replicate the example themes found on their official website. The specific theme I am focusing on is available at this link: https://getbootstrap.com/docs/4.3/examples/pricing/ Unfortunately, ...

Using Vue's V-IF directive to compare dates

On my website, I have an object that contains a field named available_at with the date in the format of 2019-08-08 I have a working HTML table utilizing Vue bindings but I am unsure how to compare the timestamp above using the built-in Date.now() method ...

Using expect() within the .then() function when writing Jasmine unit tests for AngularJS

I'm currently struggling with the .then() function while trying to implement Jasmine unit testing. Here is the code that's giving me trouble: describe("getBuilding", function () { it("checks getBuilding", function () { var id_building = 4; ...