Implement jQuery to dynamically assign an "Active" class to tab elements based on the current page being loaded

INQUIRIES I have include:

  • How do I apply a class to an element using jQuery, or any other method, for the active tab?

  • Ensure that the dropdown tab appearing is the one containing the active tab, not always the Company one.

In essence, I want the active tab to slide down from another tab and ensure that the dropdown tab corresponds with the active tab.

This is the current setup:

$(document).ready(function(){

// Hides all other dropdowns
  function slideAllUp(obj)
  {
     $(".hideothers").each(function(){
       
       if ($(this)[0] != obj[0])
       {
         $(this).hide(); //perform on all except self.
       }
     })
  }

// Assigns active tab (adds class to active tab)
  $('.sidebar-menu li').on('click', function () {

      $(this).siblings().removeClass('clicked');
      $(this).addClass('clicked');


  });
  

$(".hideothers").hide();

// Account dropdown
    $(".slidingDiv_account").hide();
    $(".show_hide_account").show();
    
    $(".show_hide_account").click(function(){
    slideAllUp($(".slidingDiv_account"));
    $(".slidingDiv_account").slideDown();
    });

// Company dropdown
    $(".slidingDiv_company").show();
    $(".show_hide_company").show();
    // $(".hideothers").hide();
    
    $(".show_hide_company").click(function(){
    slideAllUp($(".slidingDiv_company"));
    $(".slidingDiv_company").slideDown();
    });

// Invest dropdown
    $(".slidingDiv_invest").hide();
    $(".show_hide_invest").show();
    // $(".hideothers").hide();
    
    $(".show_hide_invest").click(function(){
    slideAllUp($(".slidingDiv_invest"));
    $(".slidingDiv_invest").slideDown();
    });

  });
ul.sidebar-menu , ul.sidebar-menu li ul.sub{
    margin: -2px 0 0;
    padding: 0;
}

ul.sidebar-menu {
    margin-top: 75px;
}

ul.sidebar-menu li a span{
    display: inline-block;
}

ul.sidebar-menu li a{
    color: #aeb2b7;
    text-decoration: none;
    display: block;
    padding: 15px 0 15px 10px;
    font-size: 12px;
    outline: none;
    -webkit-transition: all 0.3s ease;
    -moz-transition: all 0.3s ease;
    -o-transition: all 0.3s ease;
    -ms-transition: all 0.3s ease;
    transition: all 0.3s ease;
}

ul.sidebar-menu li a.active, ul.sidebar-menu li a:hover, ul.sidebar-menu li a:focus {
    background: #68dff0;
    color: #fff;
    display: block;

    -webkit-transition: all 0.3s ease;
    -moz-transition: all 0.3s ease;
    -o-transition: all 0.3s ease;
    -ms-transition: all 0.3s ease;
    transition: all 0.3s ease;
}


ul.sidebar-menu li a i {
    font-size: 15px;
    padding-right: 6px;
}

ul.sidebar-menu li a:hover i, ul.sidebar-menu li a:focus i {
    color: #fff;
}

ul.sidebar-menu li a.active i {
    color: #fff;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<!--sidebar start-->
      <aside>
      <!-- Start of Toggle -->
        <div id="sidebar"  class="nav-collapse ">
          <!-- sidebar menu start-->
          <ul class="sidebar-menu" id="nav-accordion">

          <div class="top_menu">
            <span class="show_hide_company">Company<i class="fa fa-briefcase"></i></span>
            <span class="show_hide_invest">Invest<i class="fa fa-line-chart"></i></span>
            <span class="show_hide_account">Account<i class="fa fa-user"></i></span>
          </div><br>


          <!-- Account Dropdown --> 
            <div class="slidingDiv_account hideothers"> <!-- Start of toggle -->
              <li>
                <a href="/inbox">
                  <i class="fa fa-inbox"></i>
                  <span>Inbox</span>
                </a>
              </li>
              <li>
                <a href="/users-companies">
                  <i class="fa fa-search"></i>
                  <span>Users & Companies</span>
                </a>
              </li>
              <li>
                <a href="/account">
                  <i class="fa fa-pencil"></i>
                  <span>Edit Account</span>
                </a>
              </li>
              <li>
                <a href="/request-help">
                  <i class="fa fa-question"></i>
                  <span>Request & Help</span>
                </a>
              </li>
            </div> <!-- end of toggle -->


          <!-- Company Dropdown -->
            <div class="sub slidingDiv_company hideothers" style="display: block;"> <!-- Start of toggle -->
              
              <%if Company.where(:user_id => current_user.id).count==0 || current_user.premium%>
              <li>
                <a href="/companies/new">
                  <i class="fa fa-star"></i>
                  <span>Start a Startup</span>
                </a>
              </li>
              <%end%>

              <%if Company.where(:user_id => current_user.id).count>=1%>
              <li>
                <a href="/companies">
                  <i class="fa fa-building"></i>
                  <%if Company.where(:user_id => current_user.id).count==1%>
                    <span>Company</span>
                  <%elsif Company.where(:user_id => current_user.id).count>1%>
                    <span>Companies</span>
                  <%end%>
                </a>
              </li>
              <%end%>
              
              <li>
                <a href="/trade">
                  <i class="fa fa-exchange"></i>
                  <span>Trade</span>
                </a>
              </li>

              <li>
                <a href="/profit-and-loss">
                  <i class="fa fa-list"></i>
                  <span>Profit & Loss</span>
                </a>
              </li>

              <li>
                <a href="/upgrade">
                  <i class="fa fa-arrow-up"></i>
                  <span>Upgrade</span>
                </a>
              </li>

              <li>
                <a href="/employes/find">
                  <i class="fa fa-search"></i>
                  <span>Find Employes</span>
                </a>
              </li>
              

            </div> <!-- end of toggle -->
          

          <!-- Invest Dropdown -->
            <div class="sub slidingDiv_invest hideothers" style="display: block;"> <!-- Start of toggle -->
              <li>
                <a href="/stock-market">
                  <i class="fa fa-line-chart"></i>
                  <span>Stock Market</span>
                </a>
              </li>

              <li>
                <a href="/find-investors">
                  <i class="fa fa-search"></i>
                  <span>Find Investors</span>
                </a>
              </li>

              <li>
                <a href="/investments">
                  <i class="fa fa-list"></i>
                  <span>Invest</span>
                </a>
              </li>

              <li>
                <a href="/properties">
                  <i class="fa fa-bank"></i>
                  <span>Properties</span>
                </a>
              </li>

              <li>
                <a href="/advertisement">
                  <i class="fa fa-tv"></i>
                  <span>Advertisment</span>
                </a>
              </li>

            </div> <!-- end of toggle -->
          

            <li class="mt">
              <!--                       <a href="index.html"> -->
              <!--                           <i class="fa fa-search"></i> -->
              <!--                           <span>Browse Events</span> -->
            </a>
          </li>

        </ul>
        <!-- sidebar menu end-->
      </div>
    </aside>
    <!--sidebar end -->

Clicking on Company, Account, and Invest will reveal the "dropdowns".

Note: Each tab click initiates a new page load.

Answer №1

To ensure only one link is active at a time, you can create a click handler for the li element. Remove the "active" class from all sibling elements and add the "active" class to the clicked li item.

Below is the example using jQuery:

 $('.sidebar-menu li').on('click', function () {

      $(this).siblings().removeClass('active');
      $(this).addClass('active');

  });

Check out this working example (click on Run snippet):

$(document).ready(function(){

  $('.menu li').on('click', function () {
      
      $(this).siblings().removeClass('active');
      $(this).addClass('active');
      
  });
    
});
.active{
    
color:green;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul class="menu">
    <li class="active">Menu Item 1</li>
    <li> Menu Item 2</li>
     <li> Menu Item 3</li>
     <li> Menu Item 4</li>
    
</ul>

Access the fiddle link here

UPDATE:

You can apply the same logic to your menu by adjusting the class names as needed:

 $('.top_menu span').on('click', function () {

         $('.top_menu span').removeClass('active');
          $(this).addClass('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

There was an issue stating that valLists is not defined when paginating table rows with AngularJS and AJAX

I found a helpful code snippet on this website for implementing pagination in AngularJS. I'm trying to adapt it to work with data from a MySQL DB table called 'user', but I keep running into an issue where the valLists variable is undefined, ...

Prevent the user from selecting an option if the value is already present

In the process of creating a library membership form, I am utilizing an ajax request to populate the student list in a select option. The goal now is to disable the options for students who are already members of the library. View of the Form <div cla ...

What is the best way to include an Interval in a button element?

I am currently working on developing an application that will automatically take a picture every minute using the camera. I want to implement a button tag with an interval so that when the application is running, it will capture an image every minute. i ...

Error message: An uncaught promise was encountered, despite adding a catch function. I am unable to identify the issue causing this error

Why is the added catch block not functioning properly? function maxRequest(url = ``, times = 3) { // closure function autoRetry (url, times) { console.log('times = ', times); times--; return new Promise((resolve, reject) => ...

The 'substr' property is not found in the type 'string | string[]'

Recently, I had a JavaScript code that was working fine. Now, I'm in the process of converting it to TypeScript. var ip = req.headers['x-forwarded-for'] || req.connection.remoteAddress; if (ip.substr(0, 7) == "::ffff ...

eliminating reliance on promises

I understand the importance of promises, however I am faced with a challenge as I have multiple old functions that currently operate synchronously: function getSomething() { return someExternalLibrary.functionReturnsAValue() } console.log(getSomething( ...

DataTables ajax feature is not functioning

Looking to implement AJAX in this table using the following code snippet: $('#example').DataTable({ 'serverSide': true, "bPaginate": false, "info": false, "iDisplayLength":20, "bLengthChange":false, 'ajax&a ...

Transferring data from JavaScript to PHP using the $.ajax method for storing information in a MySQL database

I am attempting to make a POST call from a JavaScript file to a PHP file in order to insert a variable into a MySQL database. Here are the basic files I am working with: 1° PHP file for sending the call <html> <head> <script ...

Limiting overflow:visible to input and select fields only

I'm currently facing an issue with a Lightning Web Component in Salesforce, however, I believe the root cause of this problem is not specific to this platform. Within my container div, I have row divs displaying select/combobox fields that need to ex ...

choosing a suggestion by onkeypress (jquery-ajax) utilizing the arrow keys pointed up and down

I have implemented an auto-suggest box with a fancy apple style suggestion box. Everything is functioning well, but I would like to enable users to select a value from the suggestion box using the up or down arrow keys. How can I implement this functionali ...

Unable to transform object into a primitive value using imported JSON data

https://i.sstatic.net/HcY5M.png I am currently working on creating a Vuetify component dynamically within a Nuxt project, as discussed in this Stack Overflow thread (Using different text values with Vuetify component). To achieve this, I am importing and ...

Tips for effectively testing an Angular directive

I'm having trouble testing an Angular directive due to encountering the following unexpected error: Error: Unexpected request: GET /api/players/info It seems that the issue may stem from references to my controller within the directive definition ob ...

The search feature in my React Pagination is not performing as effectively as expected

I recently set up a React app that interacts with a MongoDB database using an Express Server. The pagination feature is working smoothly, but I encountered an issue with the search function. It only works when typing in the input box; deleting characters d ...

Arranging elements in two arrays in either ascending or descending order

Looking to implement sorting functionality for the "fuel.name" value within this array... const orders = [ { "_id":"5d14a31490fb1e0012a3d2d8-1", "orderId":"0JL5ORM0JT-1", "created":"2019-06-27T11:05:56.377Z", "createdDate":"2019-06-2 ...

Using JavaScript to show content in a textarea field

In my index.jsp file, I have implemented the following code to populate two textareas, INPUT_TEXT and INPUT_TEXT2, with processed data. This involves passing the text through a servlet, a Java class, and finally displaying the preprocessed results in the s ...

Implementing PHP code to prevent the submission of forms with invalid inputs

When working on a form validation process in PHP, I encountered a challenge in preventing the form from being submitted to the database when there are errors in the input fields. While I was able to display error messages for invalid inputs upon submitti ...

React - Highcharts Full Screen dark overlay

I am currently working on integrating highcharts/highstock into my application, and I have encountered an issue with the full screen functionality. The challenge I am facing is setting a fixed height for my charts while also enabling the option to view ea ...

Floating elements are misaligned and not laying out correctly

I've encountered an issue where the footer div is appearing behind the right-hand side div. I have a central container div with two floated divs next to each other, and the footer is separate. I've spent hours trying to fix it but can't figu ...

Activate the submission button on AngularJS once a correctly formatted email is provided

Currently working on an AngularJS demo to better understand its functionalities. The next task on my list is to enable the submit button only when a valid email address is entered. I'm seeking guidance on how to approach this and what concepts I need ...

Executing JavaScript functions externally from the Angular 6 application

I have a unique scenario where my angular 6 app is embedded within another application that injects JavaScript to the browser to expose specific functionalities to the angular app. For example, when running my angular app within this external application, ...