Creating a dynamic sidebar menu with clickable submenus through jQuery and CSS for a user-friendly experience

<div id="sidebar" class="sidebar">
   <div class="slimScrollDiv" style="position: relative; overflow: hidden; width: auto; height: 100%;">
      <div data-scrollbar="true" data-height="100%" data-init="true" style="overflow: hidden; width: auto; height: 100%;">
         <ul class="nav">
            <li class="has-sub">
               <a href="#"> <span>Home</span></a>
            </li>
            <li class="has-sub expand">
               <a href="javascript:;"> <b class="caret"></b> <span>Accounts</span> </a>
               <ul class="sub-menu">
                    <li><a class="load" href="#">Agent Creation</a></li>
                    <li><a class="load" href="#">Customer  Create</a></li>
                    <li><a class="load" href="#">Customer FD Create</a></li>
                    <li><a class="load" href="#">Customer RD Create</a></li>
                    <li><a class="load" href="#">Partner Create</a></li>
                    <li><a class="load" href="#">Partner FD Create</a></li>
               </ul>
            </li>
         </ul>
      </div>
   </div>
</div>

Can someone assist me with implementing a feature where the sidebar menu and submenus highlight onclick using Jquery and CSS?

Answer №1

$(function() {
  $('.menu>li>a, .submenu>li>a').click(function(item) {
    $('.menu>li, .submenu>li').removeClass('active');
    $(this).parent().addClass('active');
  });
});
.menu,
.submenu {
  list-style: none;
  margin: 0;
  padding: 0;
}

.submenu {
  padding-left: 5px;
}

.menu>li.active>a,
.submenu>li.active>a {
  background: #eee;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<div id="sidebar" class="sidebar">
  <div class="slimScrollDiv" style="position: relative; overflow: hidden; width: auto; height: 100%;">
    <div data-scrollbar="true" data-height="100%" data-init="true" style="overflow: hidden; width: auto; height: 100%;">
      <ul class="menu">
        <li class="has-sub">
          <a href="#"> <span>Home</span></a>
        </li>
        <li class="has-sub expand">
          <a href="javascript:;"> <b class="caret"></b> <span>Accounts</span> </a>
          <ul class="submenu">
            <li><a class="load" href="#">Agent Creation</a></li>
            <li><a class="load" href="#">Customer  Create</a></li>
            <li><a class="load" href="#">Customer FD Create</a></li>
            <li><a class="load" href="#">Customer RD Create</a></li>
            <li><a class="load" href="#">Partner Create</a></li>
            <li><a class="load" href="#">Partner FD Create</a></li>
          </ul>
        </li>
      </ul>
    </div>
  </div>
</div>

Answer №2

Use .removeClass() and .addClass() depending on your click action. To highlight along with the parent element, you can utilize .closest().

$('ul > li> a').on('click', function() {
  $('ul > li> a').removeClass('highlight')
  $(this).addClass('highlight');
  $(this).closest('ul').closest('li').find('a:eq(0)').addClass('highlight');

});
.highlight {
  background: #d3d3d3;
  border-radius: 10px;
  padding: 0px 20px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.0/jquery.min.js"></script>
<div id="sidebar" class="sidebar">
  <div class="slimScrollDiv" style="position: relative; overflow: hidden; width: auto; height: 100%;">
    <div data-scrollbar="true" data-height="100%" data-init="true" style="overflow: hidden; width: auto; height: 100%;">
      <ul class="nav">
        <li class="has-sub">
          <a href="#"> <span>Home</span></a>
        </li>
        <li class="has-sub expand">
          <a href="javascript:;"> <b class="caret"></b> <span>Accounts</span> </a>
          <ul class="sub-menu">
            <li><a class="load" href="#">Agent Creation</a></li>
            <li><a class="load" href="#">Customer Create</a></li>
            <li><a class="load" href="#">Customer FD Create</a></li>
            <li><a class="load" href="#">Customer RD Create</a></li>
            <li><a class="load" href="#">Partner Create</a></li>
            <li><a class="load" href="#">Partner FD Create</a></li>
          </ul>
        </li>
      </ul>
    </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

Incorporating information collected from a modal form into a table using vue.js

insert code hereThis single page application allows users to input data into a modal, which is then automatically added to a table on the main page. var modal = document.getElementById('modalAdd'); var modalBtn = document.getElementById(' ...

Design a button for removing the selected value in select2

Can anyone provide some guidance on using select2? I am working with 2 select2 elements, and I want the selected value to be displayed on a button instead of in the input area of the select2. This way, the select2 will still display the placeholder text. ...

Is there a viable substitute for websockets that can be utilized on shared hosting platforms?

Are there any viable alternatives for websockets that can be used with shared hosting? While I'm aware of node.js, socket.io, and Express.js, I'm unable to use them in a shared hosting environment. If there are other options available for creatin ...

Issue with my "message.reply" function malfunctioning in Discord.JS

I'm currently learning how to use discord.Js and I am facing an issue with my message.reply function not working as expected. I have set up an event for the bot to listen to messages, and when a message containing "hello" is sent, it should reply with ...

Leverage the Power of Two AngularJS Factories

Can I efficiently use two Factories in AngularJS by calling one from the other? Here's the Scenario: I have a Factory that returns an Array. This Factory is responsible for checking if the data to populate this Array already exists in local SQL Stor ...

Navigate within a div using arrow keys to reposition another div

As a newcomer to JavaScript, I am facing some challenges. My goal is to use arrow keys to move a small div inside a larger div. However, the code below is not functioning as expected. Here is the HTML and CSS: <div id="rectangle"> <div id="s ...

Steps to retrieve an ext.js grid using data from a database

I've been struggling to make a basic Ext.js application work, which is supposed to pull data from a database and show it in an Ext.js grid. However, all I keep getting is "Failure:true". If you could help me identify the mistake, that would be great. ...

Discover the steps for dynamically integrating ionRangeSliders into your project

Recently, I integrated ionRangeSlider to display values to users using sliders. To set up a slider, we need to define an input tag like this: <input type="text" id="range_26" /> Then, we have to use jQuery to reference the input tag's ID in or ...

Ways to position a flexbox child at the bottom of its container

Utilizing Flexbox to arrange different content in a panel, there is an issue with the positioning of icons within each panel. The fourth icon wraps around and aligns with the first one at the top of its container, instead of lining up with the third icon a ...

Invoke a bounded function within an Angular directive using the ng-click event

I was wondering if it's possible to invoke a bound function within a directive by clicking on a specific part of a div. Currently, I have a div with an inner div that acts as a button for expanding the main div. The larger div has a directive associat ...

Combining Array Attributes to Create a New Property as a 'JSON String'

I'm attempting to combine the attributes of an array into a JSON-like string as a new attribute. For example: [{ { "orderNo":"1", "description":"Item 1", "note": "Note 1" }, { "orderNo":"2", "description":"Item 2", ...

Unexpected element layout issues

Attempting to create a basic website that utilizes the flickr api, retrieves photos and details, and displays them using bootstrap. However, there seems to be an issue that I am unsure how to resolve. Currently, my code is functioning like so: https://i.s ...

Identify the browser dimensions and implement CSS styling for all screen resolutions

I am currently facing an issue with a function that I have created to apply CSS changes to a menu based on browser resizing and different resolutions. The problem lies in the fact that my function does not seem to be correctly interpreted by the browser. W ...

What is the best way to create individual Menu items in a React/MUI navigation bar?

I am currently developing a navigation bar for an application, and I seem to be facing an issue with differentiating between multiple Menu/MenuItem elements. No matter what approach I take, both Menus and their respective MenuItems end up directing to the ...

Leverage the power of getServerSideProps when working with Dynamic Routes

I have been working on implementing getServerSideProps in my file named [username].js which utilizes dynamic routing. Next.js requires the use of both getStaticPaths() and getStaticProps({ params }) for dynamic routing. However, there seems to be an issu ...

Unable to retrieve a return value from an asynchronous waterfall function within a node module

A custom node module that utilizes async waterfall is working properly when run independently, but the AJAX callback does not receive the return value. //Node module var boilerplateFn = function(params){ async.waterfall([ function(callback){ ...

Utilizing pop-up info boxes

After thoroughly reviewing the documentation on Imagemapster's website and browsing several posts, I am still struggling to get the tooltips working correctly. I attempted to share my HTML and JS code on jsfiddle.com without success, so I have provide ...

jQuery: Managing and modifying values for dynamically generated input elements

Hello, I am currently working with the latest version of jQuery and have a table set up where clicking on the "Add" button appends a row of inputs. My goal is to calculate the total price for each particular product based on keyup events (i.e., qty * price ...

The export of 'alpha' is not available in the '@mui/system' module

Help! I am encountering an error related to the @mui/material library. I have already looked into the package.json file of mui/system and it seems that 'alpha' is exported in it. ./node_modules/@mui/material/styles/index.js Attempted import erro ...

Two boxes each taking up half of the width, with content placed inside a container

How can I achieve the appearance seen in this image? https://i.sstatic.net/2oZW8.png The layout consists of four columns using regular Bootstrap code. The first two columns should have a white background within a .container, while the other two columns s ...