Creating dynamic dropdown lists that automatically apply the active class to the chosen option

Here is the JSTL tags code I am using:

<ul class="megamenu skyblue">
 <!--1st level of categories  -->
 <c:forEach var="item1" items="${shoppingCart.categories}">
  <li id="headerCategory" class="grid" style="border-right: 1px solid #e5edec;">
   <a  class="inactive color1" href="#">${item1.name}</a>
   <div class="megapanel">
    <div class="row">
     <fmt:parseNumber var="i" type="number" value="${item1.id}" />
     <c:forEach var="item2" items="${shoppingCart.subcategories}">
      <c:if test="${item2.parentCategory.id==i}">
       <div class="col1">
        <div class="h_nav">
         <h4>
          <a href="#" onclick="dispProductCategoryWise('${item2.name}','${item2.id}')">${item2.name}</a>
         </h4>
         <ul>
          <fmt:parseNumber var="j" type="number" value="${item2.id}" />
          <c:forEach var="item3" items="${shoppingCart.subcategories}">
           <c:if test="${item3.parentCategory.id==j}">
            <li>
             <a href="#" >
              &#9830;${item3.name}
             </a>
            </li>
           </c:if>
          </c:forEach>
         </ul>
        </div>
       </div>
      </c:if>
     </c:forEach>
     <%-- <img src="${pageContext.request.contextPath}${item1.image}" alt=""/> --%>
    </div>
   </div></li>
 </c:forEach>
</ul>

Here is my JavaScript code:

$(document).on('click', '#headerCategory', function(){
    alert("hello");
    $('a.inactive').toggleClass('inactive active');
    //$(this).toggleClass('active inactive');
});

And here is the CSS:

.skyblue li a.active{
    background:#EF5F21;
    color: #ffffff;
}
.skyblue li a.inactive{
    background:0;
    color: 0;
}

When running the above code, all dropdown menus are active. However, I want only the selected dropdown to be highlighted.

Please assist me in highlighting the selected dropdown list.

Answer №1

I haven't personally tried this out, but you could give it a shot:

$(document).on('click', '#headerCategory', function(e){
    $(e.target).toggleClass('inactive active');
});

If that solution doesn't do the trick, you may need to approach your event handler setup in a different way:

$('#headerCategory a').on('click', function(){
    $(this).toggleClass('inactive active');
});

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

Strategies for delivering CSS exclusively to up-to-date browsers

What are some methods for serving CSS exclusively to modern browsers while displaying plain, unstyled HTML to outdated versions of Internet Explorer? I am currently employing the following approach, but I am not particularly thrilled about having my main ...

Difficulty arises in designing a tableless layout due to the issue of auto

Wondering why my page is not expanding with its content? Check out my demo on Fiddle http://jsfiddle.net/msas3/. The light blue area should determine the overall height of the page. ...

How should Hyphenopoly be properly implemented?

I am encountering difficulties while trying to integrate Hyphenopoly into a Django project. The functionality sometimes works smoothly, but other times it does not. Additionally, when viewed on a mobile browser, the hyphenation appears inconsistent or even ...

Resolving the ENOTFOUND error in Imgur API call: 443

I keep getting the same error message every time I execute the node.js code below. As someone who is new to working with Authorization Headers in node.js, I must be overlooking something. Can someone offer assistance or direct me to reliable documentatio ...

Unable to get jQuery click and hide functions to function properly

Hello, I am currently working on a program where clicking a specific div should hide its own class and display another one. However, the code does not seem to be functioning correctly. Below is my current implementation: $("#one").click(function(){ v ...

Filter out the truthy values in an array with JavaScript

I am currently working with a javascript array called 'foo' which looks like this: var foo = [false,false,true,false,true]; My goal is to eliminate all the 'true' values and only keep the 'false' ones, resulting in this arra ...

Step-by-step guide on uploading an image to Cloudinary using the MERN stack

Encountered an error when trying to submit the form: POST 400 (Bad Request) {"error":{"message":"Upload preset must be whitelisted for unsigned uploads"}} form.jsx const uploadImageToCloudinary = async (imageFile) => { ...

What is the best way to verify the content of a submission after the essential part, the 'form' tag, has been removed?

Recently, I made some changes to my code in order to improve its responsiveness which inadvertently caused issues with my jQuery code for tracking correct and incorrect answers in a short quiz. Previously, the JavaScript snippet below worked perfectly fine ...

Unexpected behavior when trying to bind data with AngularJS through a response message

Here is the code snippet: var myApp = angular.module("gameModule", []); myApp.controller("gamecontroller", function ($scope) { $scope.message = "test"; // websocket connection. var gameHub = $.connection.socketHub; $.connection.hub.star ...

Struggling with CSS, seeking improvements to align with my previous coding style

After spending a considerable amount of time working on my game, I made the decision to change my navigation bars to buttons. However, I'm facing issues while trying to finalize the style that I had previously. Here is the old code fiddle: https://js ...

Getting rid of items and bringing them back

In my current three.js project, I have implemented a feature that allows users to switch between scenes containing various mesh objects. All objects are loaded simultaneously when the page loads, but the performance is affected by the textures on these obj ...

The browser does not automatically set the Cookie

Trying to login involves making an API call using a POST HTTP request. post( postLogin(email), JSON.stringify({password: passwd}), { headers: { "Content-Type":"application/json" }, credentials: 'include' // also attempted with &a ...

What is causing the "mb-3" class from Tailwindcss to malfunction with next/link?

The "mb-3" class from Tailwindcss in this Next.js component seems to have no effect in the Y direction. However, when using the "m-3" class, it also doesn't affect the Y direction, but instead has an impact on the X direction. impo ...

Arrange HTML elements in Angular based on the scope variable

I am faced with a dilemma of displaying two divs on a page, where the order is determined by a variable in the scope. One way to approach this is by duplicating the code for the divs on the page, each time arranging them differently: <div class="optio ...

Dynamic text input and selection menu with AJAX (PHP and JavaScript)

As a student who is new to Javascript and PHP, I am trying to create a login page for my website that can verify user input in the database using AJAX. For example, when a user enters their username and password, the system should automatically check if t ...

Limiting the scrolling capability within a flex container by using the nowrap

When using flex with nowrap, it appears that the horizontal scroll bar only allows moving to the right while the items on the left remain hidden. To demonstrate this issue, I have created a sample on CodePen: http://codepen.io/anon/pen/QpgvoZ This behavio ...

Utilizing HighCharts in Your Project

View the graph here $(function () { var chart; $(document).ready(function() { chart = new Highcharts.Chart({ chart: { renderTo: 'container', type: 'column', margin: [ 50, 50, 100, 80] ...

After deployment, certain formatting elements appear to be skewed in the React application

After developing a React app with create-react-app, everything was working perfectly. However, upon deployment, I noticed that some styles weren't showing up as expected. The majority of the styling from Material UI is intact, but there are a few dis ...

Navbar display issues on mobile devices in Bootstrap

When viewing the navbar on a desktop, everything looks good. However, when looking at it on a phone, it appears distorted. How can I either disable the menu for mobile devices or what is the best way to fix this issue? Here is the code for the navbar: ...

Performing a fetch() POST request in Express.js results in an empty body object being generated

Purpose: Implement a function in fetch() to send specified string data from the HTML document, for example "MY DATA" Here is the code snippet: HTML Code: <!DOCTYPE html> <html> <body> <script type="text/javascript"> function ...