What is causing the anchors in my submenu to not function properly?

I'm currently working on a jQuery dropdown script for my navigation submenus. I have managed to implement the functionality of adding chevrons to the top-level links that have submenus, but I've encountered an issue where the 'return false' action is affecting the submenu links as well. Can anyone help me identify what I might be doing wrong? You can view the code on jsFiddle. Thank you for taking the time to assist.

<div class="nav-outter">
  <nav>
    <ul>
      <li><a href="#">Home</a></li>
      <li class="has-submenu"><a href="#">Services</a>
        <ul>
          <li><a href="#">Web Development</a></li>
          <li><a href="#">Photography</a></li>
          <li><a href="#">Multimedia</a></li>
        </ul>
      </li>
    </ul>
  </nav>
</div>

$(document).ready(function() {
  $('nav > ul > li.has-submenu').each(function() {
    $(this).find('a:first-child').each(function() {
      $(this).append('<i class="fa fa-chevron-down"></i>');
      $(this).on('click', function(e) {
        e.preventDefault();
        $(this).parent().find('ul').each(function() {
          if ($(this).hasClass('active')) {
            $(this).removeClass('active')
              .slideUp(300);
          } else {
            $(this).addClass('active')
              .slideDown(300);
          }
        });
      });
    });
  });
});

.nav-outter {
  position: relative;
  z-index: 1;
}

nav > ul {
  list-style: none;
}

nav > ul > li {
  display: inline-block;
}

nav > ul > li > a {
  padding: 3px 15px;
  font-size: 1.2em;
  color: #2c3e50;
  text-decoration: none;
}

nav > ul > li > ul {
  display: none;
  position: absolute;
  z-index: 5;
  list-style: none;
  border: 1px solid #FC4349;
  border-bottom: 0px;
  margin-left: 0px;
  padding-left: 0px;
  margin-top: 3%;
}

nav > ul > li > ul > li {
  border-bottom: 1px solid #FC4349;
}

nav > ul > li > ul > li > a {
  display: block;
  padding: 15px 25px 15px 10px;
  text-align: left;
  background: #fff;
  color: #FC4349;
  text-decoration: none;
}

Answer №1

By utilizing the find('a:first-child') method, you are selecting all the first children of every element, which in this case includes all links since they are each considered a first child.

An alternative approach would be to simply target the children of elements with the class has-submenu and iterate over them using the each function.

$('nav > ul > li.has-submenu').children('a').each(function() {

      $(this).append('<i class="fa fa-chevron-down"></i>');
      $(this).on('click', function(e) {
      .....

If you had used find('a:first') instead of find('a:first-child'), your code would have worked as well, as it targets only the first <a> within each of those elements.

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

Why does the outcome of running this code vary each time?

I've been working on a code project to create 10 bouncing balls of different colors, but I'm encountering an issue where only one or two balls appear with different colors or the animation works perfectly only 1 out of 10 times. Any thoughts on w ...

What causes the Request.Params of IHttpHandler to be accurate on the initial call, but become null on the subsequent call?

My HTML/Javascript page utilizes a jQuery ajax call to communicate with a .NET ajax handler (.ASHX). The issue arises in subsequent calls where the parameters passed in the data object are unexpectedly NULL despite being correct during the first call. Her ...

Sending a parameter between files in a React application: a step-by-step guide

I am currently working on a Pokedex website where I have Pokemon cards displaying data from a JSON file. When a user clicks on a card, a modal view appears with more detailed information about that specific card. I need help in ensuring that only the deta ...

Loading animation vanishes prior to the second ajax request being made

Whenever an ajax call is initiated, I display a loading animation that stops once the ajax call is completed. This works perfectly when there's only one ajax call in a function. However, if there are two ajax calls within the same function, the loadin ...

Attaching a geometry/mesh to its corner for resizing in three.js

I am working on creating a rectangle in three.js based on 2 coordinates. The first coordinate represents the cell where the user initially clicks, and the second coordinate is where the user drags the cursor. The rectangle that I am generating is the corr ...

Symfony 2 throws a 405 method not allowed error when attempting to use the jQuery File Upload plugin by Blue

I have integrated the OneupUploaderBundle for multi-file upload functionality in my Symfony 2 project : https://github.com/1up-lab/OneupUploaderBundle along with this plugin : The file uploads are functioning properly, but I am encountering an error in ...

I'm struggling to understand why the background-color is affecting the margins as well

Check out this code snippet: <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd"> <html> <head> <title></title> <style type="text/css"> * {border: 0px; padding: 0px;} ...

Angular Bootstrap div width not displaying fully on iPad device

My layout includes 2 columns in a single row, which is functioning properly on most devices. However, when viewed on an iPad, the layout does not span the full width of the screen. Here is a snippet of my code: <div class="row"> ...

Dynamic Route Matching in NextJS Middleware

Currently, I am in the process of developing a website that incorporates subdomains. Each subdomain is linked to a file-based page using middleware. Take a look at how the subdomains are being mapped to specific pages: app.com corresponds to /home app.com ...

Unable to relocate the cursor to an empty paragraph tag

Wow, I can't believe how challenging this issue is. My current project involves implementing the functionality for an enter key in a content editable div. Whenever the user hits enter, I either create a new p tag and add it to the document or split t ...

Error Occurs When Attempting to Call ASPX Codebehind Function from JavaScript

I am having trouble calling a function in the codebehind of my .aspx page once the window is fully displayed. I attempted to use the following code: <script type="text/javascript"> $(document).ready(function () { PageMethods.CheckFor ...

iPad is playing the incorrect file when using .play(). Any ideas on how to fix this issue?

Currently, I am developing a web application that involves a div element with dynamic text content that changes based on user interactions. To enhance the user experience, I decided to incorporate audio elements by creating an array containing correspondin ...

What factors should you consider when selecting between Bootstrap and MDBootstrap for your class usage?

My CSS skills are not very advanced. I have been using MDBootstrap for most of the styling on my project, but I am not a fan of its table styling. I would prefer to use the table CSS class from regular Bootstrap instead of MDB. I have both dependencies inc ...

What is the method for utilizing the variable from express in HTML?

Currently, I am working with Express and have the following code: app.get('/', requiresAuth(), (req, res) => res.sendFile('/db_auth_site/index.html', { title: 'Hey', message: 'Hello there!' }) ); I am trying ...

Boot up 4 collapse feature to conveniently close all other collapsible items at once

Utilizing the Bootstrap 4 Collapse component. My goal is to toggle between collapsible sections like "Categories" and "Brands", displaying only one at a time. The current issue is that multiple collapsible elements are visible simultaneously. .view-cust ...

What is causing the Brightcove Player to not load in UIWebview?

I'm new to iPhone development and I'm struggling with loading the Brightcove player into a UIWebView. I understand that iOS doesn't support Flash, but my goal is not to play the video itself, just to display the player and its thumbnail in t ...

Execute a command via a hyperlink

I have a script that displays information in a div using a button. I am trying to modify it so that it works from a link instead, but I haven't had any success yet. Any ideas on how to make this work? <script> function showCustomer(str) { va ...

`The simultaneous processing of two inputs using forkJoin`

There are two input fields on my form: Street address and Zipcode. Each field emits its value on keyup as a Subject in Angular. Before calling an API endpoint with these values, I need to ensure that both the street address and zip code values are valid. ...

Having trouble aligning items within columns using Bootstrap 4?

Even after researching and attempting solutions from previous questions, I still have not been able to achieve the desired outcome. What is the best way to align items inside columns? How can I adjust image size to perfectly fit the column width? <sec ...

I seem to be encountering an issue while looping through an array of objects. Instead of retrieving all two elements, only one object is being returned. Can

Just a heads up, I'm new to coding so please bear with me. I'm attempting to run through the "diary" array and the function "howMany" is only showing 2 'Home' elements, although there are actually 4 'Home' elements in total i ...