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

Revamp State before redirecting using React Router Dom

In my current project, I am facing an issue with redirecting after updating the state successfully. The technologies I'm using include React 16.12.0 and React Router DOM 5.1.2. Here's the scenario: I have a button that, when clicked, should updat ...

What are the precise steps to create a flawless scrolling area?

I am facing an issue with setting accurate scroll zones for my divs. Here's my ideal scroll zone location: scroll zone in red Currently, I have a maximum of 4 divs and each div should contain a total of 10 rectangles per category (concentration, boos ...

Fluctuating Values in Array Distribution

I have a set of users and products that I need to distribute, for example: The number of values in the array can vary each time - it could be one value one time and three values another time. It is important that each user receives a unique product with ...

Generating a multidimensional associative array based on user inputs from a form

What is the best way to transform form input data into a multidimensional associative array? This is how the form appears: <div id="items"> <h4>Engraving Text</h4> <div class="item" data-position="1"> <h4 id="en ...

Navigating through web pages in PHP

Is there a way to implement page navigation in PHP without reloading the entire page, similar to how Facebook operates, but without using jQuery or JavaScript? For example: For the welcome page: <a href="http://www.facebook.com/?sk=welcome"rel="nofoll ...

Trimming whitespace from strings within HTML tag attributes can be achieved using various methods

I have been reviewing the .cshtml pages of a website with the aim of adding ID attributes to various divisions and elements for testing purposes. These pages utilize AngularJS, and many of the elements I need to add ID attributes to are part of a list tha ...

JavaScript substring() function in clone is experiencing an error

I am currently working on a JavaScript function that determines whether a specific substring is present in a larger main string. For instance, if the main string is "111010" and the substring is "011," the expected result should be false since the substr ...

The HTML Canvas seems to be malfunctioning for some unknown reason

As a beginner in programming, I am struggling to understand why the code below is not working. The first three lines of the script are necessary for another part of the webpage, but I don't see how that would affect the rest of the code: <!DOCTY ...

Unexpected outcomes experienced with AJAX in ASP.NET due to javascript integration

I experimented with two methods (server and client side) for initiating a JavaScript AJAX call to post a ticket on a website and then retrieve a link containing the ticket number for tracking or editing purposes. However, both approaches yielded different ...

Tips for effectively highlighting search text within HTML content without causing any issues

I am in search of a solution that can assist me in searching for specific terms within an HTML string while also highlighting them. I have the ability to remove the HTML content from the string, but this poses the problem of losing the context of the origi ...

CSS is broken when transitioning from the development to the live site

After configuring the CSS for this site using CodeIgnitor, I placed it in the specified location: {link rel="stylesheet" type="text/css" href="<? echo base_url();?>application/assets/css/public.css" /> Although Firebug confirms that the link is ...

Unable to incorporate node-vibrant into Angular 7 project

Currently facing some challenges while attempting to integrate node-vibrant into my Angular 7 project: -Successfully imported with import * as Vibrant from 'node-vibrant';, but encountering a warning in VS Code: Module '"/Users/xxxx/Docume ...

Ways to conceal or deactivate button controls on videojs?

I am building an application using video.js and Vue. I am looking for a way to hide or disable certain controls like the play button, playback rate, and make the progress bar read-only. In the video.js documentation, I found that using controls: false hi ...

How can I set up a session in order to fetch information from a MySQL table

Can you guide me on implementing this session: (UserID is part of the login table) Session["UserID"]="usrName"; How can I incorporate the above code into the following script? using System; using System.Data; using System.Collections.Generic; using Sys ...

Why does ng-bind fail to display values from rootScope that have been set by using ng-click?

I am trying to save a variable within $rootScope. When I have the following structure, everything works fine and the second div displays the value: <html ng-app> ... <body> <button ng-click="$rootScope.pr = !$rootScope.pr"></b ...

Is there a way to prevent the window.on('beforeUnload') event from triggering when using the <a> tag?

For my project, I require a user confirmation alert to appear when the user attempts to close the window or tab using the X button. However, the window.on('beforeUnload') function also triggers for hyperlinks. How can I prevent the leave page al ...

Refresh information in AngularJS controller

I am currently working on a straightforward AngularJS script that is designed to retrieve data from a socket.io event and then integrate it into the ng template. Below is the JavaScript code I have written for this purpose: // Socket.io logic: var message ...

Prevent form submission once all tasks have been finalized

Hey there, I've been racking my brain for hours trying to solve this issue... I'm looking to disable my form after it's been submitted to prevent multiple submissions. However, every method I try seems to disable the button but also interfe ...

Utilize the $slots property when working with v-slot in your Vue application

When dealing with a specific use-case, it becomes necessary to retrieve the rendered width and height of a DOM element inside a slot. Typically, this can be achieved by accessing this.$slots.default[0].elm. However, complications arise when introducing sc ...

Nested pages are causing jQuery plugins to malfunction

I am currently working on a website, but I am facing some issues with the product listing pages and the tips and tricks page. It appears that there is an issue with jMenu and jFlipBook plugins not functioning properly. Since I didn't develop the origi ...