Activate the display of a subcategory when the class is modified

For the past couple of days, I've been grappling with this issue. Despite my best efforts, being new to javascript may be hindering my progress.

My goal is to create a Side Navigation that highlights the current section you are on. Fortunately, I stumbled upon a fantastic jquery plugin that does exactly that here

However, I'm dealing with subitems and would like to toggle the visibility of these subitems when the current section is active. Essentially, the ul should be visible if the parent list item has the class .current or if any of its sublist items have the class .current.

I understand that triggering an event on class change might be necessary for this functionality. Here's what I tried so far:

HTML Markup:

<ul id="nav">
    <li class="current"><a href="#section-1">Section 1</a></li>
    <li><a href="#section-2">Section 2</a></li>
    <li class="parent"><a href="#section-3">Section 3</a>
        <ul class="sublist">
            <li><a href="#subsection-1">Subsection 1</a></li>
            <li><a href="#subsection-2">Subsection 2</a></li>
            <li><a href="#subsection-3">Subsection 3</a></li>
        </ul>
    </li>
</ul>

I attempted the following jQuery code:

$('#nav').on('event', function(){
    $('.parent').addClass('current').trigger('visibility');
});

$('.parent').on('visibility', function(){
    $('.parent .sublist').addClass('visible');
});

Essentially, I aim to replicate the behavior seen in Bootstrap documentation. As you scroll down, Glyphicons become visible at specific sections; similarly, the subitems expand once you reach them here

The SASS styling applied to the navigation structure so far looks like this:

.overview{
    transition: .3s all;

    ul{
        margin-left: 10px;

            ul{
                max-height: 0;
                transition: max-height 1s ease-out;
                overflow: hidden;
            }
    }
}

.current{
    > a{
        font-weight: $bold;
    }

    ul{
        max-height: 9999px !important;
        transition: max-height 1s ease-out;
    }
}

Though I managed to display the sublist when the parent is set to current, it disappears once the child becomes current. Therefore, I suspect some javascript intervention is necessary

Answer №1

Aha, I understand now!

One possible approach could be to create a function that monitors scrolling and adds a class to the corresponding item in the navigation bar when a certain point is reached.

You can achieve this without using a plugin with a script like this:

 var checkScroll = function(){
    $('.container p').each(function(){
      var item = $(this).offset().top,
          $window = $(window),
          navItem = $('#nav a[data-id="'+$(this).data('id')+'"]');

      if ($window.scrollTop() >= item) {
        if (!navItem.hasClass('current')) {
          $('#nav .current').removeClass('current');
          navItem.addClass('current');
        }
      }
    });
  };

  $(window).scroll(function(){
     checkScroll(); 
  }); 

You can see an example at http://codepen.io/jhealey5/pen/GjJFI - You can customize it as needed.

If my interpretation is accurate :)

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

``There is an issue with the Nodejs required module variable not updating even after deleting

Feeling puzzled about the situation. Module 2 is supposed to require a variable from module 1, but even after deleting the cache, the variable in module 2 refuses to update when changes are made. Sample Module 1 var num = 6 function changeNum(){ num = ...

Modifying the action of a form using jQuery

I've been searching for solutions to my issue, but so far I haven't been able to make it work... I'm attempting to create a form action based on a menu selection. It seems like there's an error somewhere and I could use some help! $(" ...

Error encountered in jQuery call during Page_Load

Here is the code I am using to register a javascript function on Page_Load (I also tried it on Page_Init). This javascript function switches two panels from hidden to shown based on a parameter when the page loads: protected void Page_Load(object sen ...

The functionality of jQuery autocomplete is hindered when trying to utilize a remote data source

HTML: <input type="text" id="shop-id"> JS: $(document).ready(function(){ $( "#shop-id" ).autocomplete({ source: "/ticket/get_sids", select: function(event, ui){ //... } }); }); Encountering an unusual i ...

Troubleshoot: Python in Databricks Encountering Attribute Error when Sending HTML Emails - 'list' object lacks 'encode' attribute

Looking to send an HTML-formatted email from Databricks using Python, but encountering the AttributeError: 'list' object has no attribute 'encode' error. Despite extensive research through various resources like blogs and stack overflow ...

"Trouble with making jQuery AJAX calls on Internet Explorer versions 8 and 9

I've been searching for the answer to this problem without any luck. I have a page with jquery ajax calls to an API service. It works well in Chrome, Safari, Firefox, and IE 10, but fails in IE 9 and 8. Here is the code: $.ajax({ ...

Implementing event handling for external modules using on method in Node.js

I have been utilizing the request module (available at https://www.npmjs.com/package/request) for executing a series of http requests in my application. However, I am currently facing an issue while attempting to integrate a logging feature into it. I am s ...

Adjust 3D Model in ThreeJS to Fit Bounding Box Dimensions

I need to adjust the scale of the imported GLB Model to match the size of a cube in my scene. This is necessary to ensure that the model remains within the shadow casting areas and is large enough to display the shadows effectively. I have already determi ...

Can an element be targeted for hover in CSS without it being a child element?

In my HTML code, I have an <aside> and a <header>. The <header> contains a child element called container, which has some children including one named burger bar. What I am trying to achieve is that when I hover over the burger bar elemen ...

Tips for accessing your unique custom font

The website I'm currently on is using a unique font named zee family. I want to know how I can download or save this specific font style for my personal use. Any assistance with this would be greatly valued. ...

Tips for achieving AngularJS 2-way binding of multiple objects within a contenteditable element, along with any surrounding text

I would like to create a collection similar to this structure: var array = [{innerText: "I was with ", index:0},{obj: "Mary", id: 1, index:1}, {innerText: " and ", index:2},{obj: "John", id: 2, index:3}]; The goal is to have a content editable div that d ...

Using Scrapy to extract data from Project Euler's website

Currently, I am working on scraping projecteuler.net using Python's scrapy library as a way to practice my skills. While there are existing implementations of similar scrapers online, they seem too complex for my needs. I simply want to save the probl ...

organizing various kinds of data values within an array

Within this array, I have two types of variables - an integer and a string. My goal is to sort the array either alphabetically or by the length of the string. However, it seems that the sorting algorithm is prioritizing the integer over the string. ...

What is the proper way to select the <ul> element within an FTL template?

Can someone provide guidance on how to target a <ul> container within a freemarker template using JavaScript? My goal is to display the content of this specific <ul> element in my FreeMarker template on the web page. Any suggestions on how I ...

Creating a 2D Image Display in three.js

I'm facing a challenge with my threejs project. My goal is to have a 2D image appear on the screen when I press a key. I've done some research but haven't been able to find a solution that works for me. The methods I've tried either don ...

Some pages are receiving images from the CDN, while others are not

I am encountering some challenges while troubleshooting an issue on a website. The CDN (content delivery network) is functioning properly on some pages but not on others. Initially, I suspected a typo in the path, but that does not seem to be the case. F ...

The image file that was uploaded to our S3 storage has been detected

I'm attempting to upload an image created by cropperjs to a DigitalOcean space. To achieve this, I am utilizing a pre-signed URL and performing a put request using Axios. The problem arises when I try to open the uploaded image, as it appears to be ...

Identifying PHP post/get variables with jQuery

I am working on a PHP project where I have a form that sends a variable to the same page. I am looking to create a jQuery script that will show or hide a specific div based on the value sent by the form. Here is the form code I have in my PHP file: < ...

Testing Angular Reactive Forms: Synchronizing HTML and Control values mismatch

I have been diligently following the Angular reactive form unit testing tutorial here, but I continue to struggle with keeping the control value and HTML value in sync. Below is how I've implemented it; note that I am trying to use setValue along with ...

Steps for transforming Dec 2 1991 12:00AM into 12/02/1991

const dobString = "Dec 02 1991 12:00"; const newDate = dobString.substring(0, dobString.length - 6); const birthDate = $filter('date')(new Date(newDate), 'mm/dd/yyyy'); ...