Steps to activate the main menu of a navigation bar after choosing a submenu:

I am currently working on a bootstrap nav bar that has main menus and submenus. I am trying to figure out how to make one of the main menus highlighted after selecting its submenu. For example, when I choose "For Shippers", I want "HOW IT WORKS" to become active and highlighted. However, my current code only allows me to make the main menu active if it is selected, not the submenu. I believe adding some JavaScript or JQuery to my existing code can solve this issue, but I am not very experienced with JQuery. Any assistance would be greatly appreciated.

$(function() {
  // highlight the current nav
  $("#index a:contains('HOME')").parent().addClass('active');
  $("#shippers a:contains('SHIPPERS')").parent().addClass('active');
  $("#carriers a:contains('CARRIERS')").parent().addClass('active');
  $("#carrier_signup a:contains('First Time User Sign Up')").parent().addClass('active');
  $("#carrier_login a:contains('Current User Login')").parent().addClass('active');
  $("#about a:contains('ABOUT US')").parent().addClass('active');
  $("#contact a:contains('CONTACT US')").parent().addClass('active');
  $("#howitworks a:contains('HOW IT WORKS')").parent().addClass('active');
  $("#hiw_shippers a:contains('FOR SHIPPERS')").parent().addClass('active');
  $("#hiw_carriers a:contains('FOR CARRIERS')").parent().addClass('active');

  // make menus drop automatically with hover for dropdown menu
  $('ul.nav li.dropdown').hover(function() {
    $('.dropdown-menu', this).fadeIn();
  }, function() {
    $('.dropdown-menu', this).fadeOut('fast');
  });
})
.navbar-default {
  background-color: #0064ff;
}

.navbar-default .navbar-brand {
  color: white;
}

.navbar-default .navbar-nav>li>a {
  color: white;
}

.navbar-default .navbar-nav>li>a:hover {
  background-color: #E8E8E8;
}

.navbar {
  margin-bottom: 0;
}

.icon-bar {
  margin: -20px 0px -20px 3px;
}

.active {
  background-color: #E8E8E8;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<nav class="navbar navbar-default">
  <div class="container-fluid">
    <div class="navbar-header">
      <button type="button" class="navbar-toggle" data-toggle="collapse" data-target="#myNavbar">
        <span class="icon-bar"></span>     <span class="icon-bar"></span>     <span class="icon-bar"></span>   </button>  
   <a class="navbar-brand" href="#">&nbsp;&nbsp;America <span class="glyphicon glyphicon-star-empty"></span>Shipping Choice
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</a>
   </div>
    <div class="collapse navbar-collapse dropdown" id="myNavbar">
      <ul class="nav navbar-nav">
        <li><a href="index.php">HOME</a></li>
          <li><a href="Shippers_login.php">SHIPPERS</a></li>
        
                        <li class="dropdown">
                          
          <a class="dropdown-toggle" data-toggle="dropdown" href="#">CARRIERS
                  <span class="caret"></span></a>
                                    <ul class="dropdown-menu">
                                                <li><a href="carrier_signup.php">First Time User 
                                                 <span class="glyphicon glyphicon-arrow-right"></span> Sign up</a></li>
                                 <li><a href = "carrier_login.php">Current User <span class="glyphicon glyphicon-arrow-right"></span> Login</a></li>
        
                                </ul>
                    </li>

  
  
<li><a href="about.php">ABOUT US</a></li>
        
              <li><a href="contact.php">CONTACT US</a></li>
              <li class="dropdown">
                            <a class="dropdown-toggle" data-toggle="dropdown" href="#">HOW IT WORKS
                                        <span class="caret"></span></a>
                              <ul class="dropdown-menu">
                                  <li><a href="howitworks_shippers.php"><span class="glyphicon glyphicon-arrow-right"></span> For Shippers</a></li>
                                  <li><a href="howitworks_carriers.php"><span class="glyphicon glyphicon-arrow-right"></span> For Carriers</a></li>
                               </ul>
                      </li>
             </ul>
       </div></div></nav>

Answer №1

Are you looking to apply a highlight effect on hover or click? Because, if it's triggered by a click, there may not be much of a point in highlighting its parent as the user will likely navigate to another page.

However, if it's on hover, you can incorporate the following CSS:

li:hover > a {background-color: #E8E8E8;}
li:hover a:hover {background-color: #E8E8E8;}

@

If you prefer a click action, add this JavaScript code:

$(".dropdown-menu > li > a").on("click",function(x){
    var target = $(this).closest(".dropdown").children("a");
    if(!target.hasClass("active"))
        target.addClass("active");
    x.preventDefault();
});

$("li").on("mouseover",function(){
    var target = $(this).children("a");
    if(target.hasClass("active"))
        target.removeClass("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

Unable to retrieve file paths for assets using Node.js Server and Three.js

I am facing challenges when it comes to loading 3D models from a folder on my computer using a localhost node.js test server with the three.js library. Below is my app.js file that I execute via command line in the project directory using the 'node a ...

Dynamic classroom experience featuring a bootstrap sidebar

I am having an issue with changing the active class of the sidebar after a click event. I have tried using Bootstrap and implemented some JavaScript code, but it doesn't seem to be working properly. $(function(){ $('.sidebar1 a').filt ...

Avoid creating empty blocks in ASP.NET MVC

I'm working on some back-end code Take a look at the code snippet below [HttpGet] public ActionResult GetQuestions() { var _id = TempData["ID"]; var questBlock = db.QuestionBlocks .Where(x => x.Interview_Id == ...

Is the image loading promptly? Do we need to adjust the resolution?

Is there a way to decrease the loading time of images? For instance, if I have 20 identical images on my homepage (each sized at 1920x1080) This is the image: I want to crop the image to a fixed size. Here's the CSS code I am using: .startpage_im ...

Associating models using a many-to-many relationship in Sequelize unexpectedly restricts the ability to modify attributes in the join table

I am in the process of incorporating a voting feature into my app, allowing users to vote on responses from other users. The backend of my Node app is built using Express and Sequelize. Currently, I am utilizing a SQLite database for testing convenience. ...

New to Angular: Getting Started with NgModel Binding

Novice query: I am facing an issue with a simple input type=text element linked to ng-model="xyz.zyx", where xyz refers to an object. In my controller, I initialize this object and set the value for the property zyx as shown below: xyz { zyx: $scope.zz ...

Choosing a default selection in a nested v-for loop for a select box

Currently, I have a list of items that users can add new items to. Each item is required to have a select box, and the selected value from the select box should be assigned as the item's value. In an attempt to bind the select box to the item using t ...

The function d3.json() does not support googleoverlay

As a newcomer to coding, I am currently working on incorporating the code found at https://bl.ocks.org/mbostock/899711. Instead of using a local .json file, I have opted to read JSON data from a URL. However, I encountered an issue where the LAT and LONG v ...

What could be causing the additional iteration in my for loop and preventing it from copying to the intended cells?

Every time I execute my script, it seems to run one additional time than necessary. For instance, it generates a PDF and marks a cell as processed below the last row. Another issue is that the URLs do not align correctly with their corresponding names. I ...

The vertical alignment of the wrapper div does not support multiple lines of text

I am having trouble achieving vertical alignment (middle) for a div with 2 lines of text. I can do it with one line, but not two. I want one of the lines to be formatted like a h2 heading, and the other like a regular paragraph. I understand that I could s ...

Show the template when the link is clicked using Angular directive

Perhaps the question is not phrased properly, but here is the idea I am working on. I have a navbar set up with an array of countries that includes their names and coordinates. <body> <nav class="navbar navbar-default"> <div cl ...

Angular and JavaScript Performing Slide-Up Animation

Currently, I am working on creating a menu using Angular and JavaScript. My goal is to have this menu toggle between showing and hiding when a button is clicked. If you would like to view the code that I have written so far, you can check out the demo her ...

Angular 2 - The constructor of a class cannot be called without using 'new' keyword

Currently, I am working on integrating the angular2-odata library into my project. This is the code snippet I have: @Injectable() class MyODataConfig extends ODataConfiguration { baseUrl = "http://localhost:54872/odata/"; } bootst ...

Error message: Unknown scope- unable to process 'files-path' Android File provider issue

My current project involves implementing file system access in react native Android. However, when attempting to add 'files-path' in XML, an error stating "Error: Unsupported type 'files-path'" is encountered. I am utilizing the react n ...

Memory Match: Picture Edition

In this memory game, letters are used. I had considered changing it to a picture-based game, but I faced difficulty in generating images and incorporating them into the array. <script> var memory_array = ['A', 'A', 'B&ap ...

Generating dynamic arrays in JavaScript

View the working code here: http://jsfiddle.net/sXbRK/ I have multiple line segments with unique IDs, and I know which ones intersect. My goal is to create new arrays that only contain the IDs of the overlapping line segments. I do not need the IDs of l ...

AngularJS does not support the use of $(this) syntax

I have encountered an issue while developing a Chrome extension using AngularJS. I would like to add buttons to my popup page, and I want the ancestor node to disappear when a button is clicked. Here is the code snippet: in popup.html <div class="dea ...

Ways to examine attributes assigned in the controller.$onInit function in AngularJS

In a certain scenario, I am initializing some variables in the controller's $onInit method. How can I verify that these properties are being set correctly? Controller ctrl.$onInit = function () { ctrl.devices = _.cloneDeep(ctrl.formDevices); }; ...

Angular error: Trying to assign a value of type ArrayBuffer to a string type

Is there a way to display a preview of a selected image before uploading it to the server? Here is an example in HTML: <div id="drop_zone" (drop)="dropHandler($event)" (dragover)="onDragover($event)"> <p>drag one or more files to ...

React component not rendering iteration over Set in JSX

I need help figuring out how to iterate through a JavaScript Set() that is being passed down in props within a React component. I am struggling to get anything to display on the screen when attempting to loop through it: {selectedCity.forEach((key, v ...