The preventDefault() function is not functioning properly on the <a> tag

As a JavaScript beginner, I decided to create an accordion menu using JavaScript. Although I was successful in implementing it, I encountered a bug in my program.

In this scenario, uppercase letters represent first-level menus while lowercase letters represent second-level menus.

The condition I wish to apply is as follows:

If A has children, clicking on A should display "a b c d".

If A does not have children, then the click on A should simply navigate to the linked page.

I am currently facing a roadblock where the implementation works slightly differently than intended:

If A has children, when clicked on A, it shows "a b c d". If A does not have children, A is not clickable.

Below you can find the source code:

MyJSFile.js


$(document).ready(function(){
  $("#nav > li > a").on("click", function(e){
    if($(this).parent().has("ul")) {
      e.preventDefault();
    }

    if(!$(this).hasClass("open")) {
      // hide any open menus and remove all other classes
      $("#nav li ul").slideUp(350);
      $("#nav li a").removeClass("open");

      // open our new menu and add the open class
      $(this).next("ul").slideDown(350);
      $(this).addClass("open");
    }

    else if($(this).hasClass("open")) {
      $(this).removeClass("open");
      $(this).next("ul").slideUp(350);
    }
  });
});

Here is my CSS class MyCSS.css


#nav {   
  padding-left:0px;
  display: block; 
  width: 100%;
  margin: 0 auto;
}

#nav li {
    list-style-type: none;
}
#nav > li > a:hover, #nav > li > a.open {
    color: #FFF;
    background-color: #38454B;

    background-image: -webkit-gradient(
    linear,
    left top,
    left bottom,
    color-stop(0.35, #212121),
    color-stop(1, #866F4A));
    background-image: -o-linear-gradient(bottom, #212121 35%, #866F4A 100%);
    background-image: -moz-linear-gradient(bottom, #212121 35%, #866F4A 100%);
    background-image: -webkit-linear-gradient(bottom, #212121 35%, #866F4A 100%);
    background-image: -ms-linear-gradient(bottom, #212121 35%, #866F4A 100%);
    background-image: linear-gradient(to bottom, #212121 35%, #866F4A 100%);
}

#nav li ul {
    display: none;
    background-color: #CCC;
    list-style-type: none; 
}

Here is the HTML nav


 <nav>
      <ul id="nav">
        <li><a href="">Home</a></li>

        <li><a href="Go to page 1">Podiatry</a>
          <ul>
            <li><a href="Go to page 2.1">Overview</a></li>
            <li><a href="">*Podiatric Diabetes</a></li>
            <li><a href="">*Pediatric Podiatry</a></li>
            <li><a href="">*Sports Podiatry</a></li>
            <li><a href="Go to page 2.3">Tips from the podiatrist</a></li>
          </ul>
        </li>

        <li><a href="index.php?country=US&page=contact">Contacts</a>
          <ul>
            <li><a href="http:/www.google.com/search?q=web+design+icons">Link 1</a></li>
            <li><a href="http:/www.google.com/search?q=web+design+tutorials">Link 2</a></li>
            <li><a href="http:/www.google.com/search?q=web+design+user+interface">Link 3</a></li>
            <li><a href="http:/www.google.com/search?q=web+design">Link 4</a></li>
          </ul>
        </li>
      </ul>
    </nav>

Third party edit:

Check out the JSFiddle link for the code: http://jsfiddle.net/3STdc/

Answer №1

When using <code>$(this).parent().has("ul")
, it will always evaluate to true because it returns a jQuery object.

Consider using

if ($(this).parent().has("ul").length)

Check out this JSFiddle link for reference.

You can also opt for the shorter version:

if ($(this).siblings('ul').length)
, which works just as well.

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

JavaScript fails to perform without the presence of an alert

Hey there, I've come across a bit of a puzzling situation and I'm struggling to find the right words for the Title of this question. I have a javascript function that is supposed to trigger when the document has finished loading. In the initial p ...

Display/Modify HTML form

Looking for advice on how to create an interactive HTML form that displays data and allows users to edit it by clicking 'Edit' before submitting changes. Any suggestions on how to implement this functionality? ...

Mastering the jQuery animateNumber plugin: An in-depth guide to animating floating

When trying to animate a number, I encountered an issue with floats. Integers work fine, but floats seem to be causing problems. For example, if the propNumberGV is set to 5.5 and the new data.value is 10.0, the animation starts at 0.0 instead of 5.5. The ...

retrieving the AJAX response from a PHP CodeIgniter API

My issue is that I am currently working on developing a Codeigniter API. This framework is new to me, and it's my first time building an API. To get started, I followed a simple tutorial to create a basic API with the following controller: /** * @rou ...

Which function is triggered first - onclick or ng-click?

Currently, I have a button with a validation process occurring on click. The validation process triggers a web service call and other processes if successful. However, I'm uncertain if the validation is actually taking place. This is my page setup: ...

How can I ensure security measures are in place to avoid XSS attacks on user-generated HTML content?

Currently, I am in the process of developing a web application that will allow users to upload entire web pages onto my platform. My initial thought was to utilize HTML Purifier from http://htmlpurifier.org/, but I am hesitant because this tool alters the ...

Obtain the data of the highlighted row in a telerik grid directly from the client side

I am attempting to retrieve the value of a GridBoundColumn with DataField="id" using JavaScript on the client side. When the user clicks on the image button within a row, I need to extract the id for that specific row and then invoke a web method by passin ...

Is it possible to trigger a function dynamically upon checking a checkbox?

I’ve been working on a simple string formatting app using React, diving into hooks as I go. Right now, I’m tackling the part where I need to trigger specific text formatting functions based on checkbox selections. Let's say, if the lowercase chec ...

Moving an item to the top of an array in JavaScript/Vue.js: A simple guide

const a = [{ "iso2": "KH", "countryName": "Cambodia", "nationality": "Cambodian" }, { "iso2": "KI", "countryName": "Kiribati", "nationality": "I-Kiribati" }, { "iso2": "KM", "countryName": "Comoros", "nationality": "Como ...

Adjust the x-axis on the Vue.js bar chart

I'm currently working on a Vue.js Laravel application where I am trying to incorporate a bar chart using the ApexCharts module. <apexchart ref="apexChart" :options="chartOptions" :series="chartData" type="bar" ...

Troubleshooting a 404 error for an existing object: What to do?

I encounter a 404 'Not Found' error when attempting to edit a mark through my form. I am puzzled by the source of this error because in order to access this form, I require the brand ID (which can be found in the URL). Upon accessing my modifica ...

Received an undefined response from jQuery Ajax request to a webservice

I'm facing a small issue with my webservice call. I've thoroughly debugged it and confirmed that the webservice is being called with the correct value and returning the expected result. However, when I check the alert message in the completed fun ...

Sending JSON data from an iOS app to a Flask backend

Within my Flask Python web application, I store certain parameters in SessionStorage to later send back to Flask and save this data as a text file. Interestingly, the process functions perfectly on PCs and Android devices but encounters issues on iOS devi ...

Guidelines for sorting through items in Vue 3

In the past, Vue 2 allowed us to easily filter items using the | and filters syntax. However, this method is no longer supported in Vue 3. Instead, we now use the "computed" property to transform a single value into another. But what about changing values ...

Combining JSON objects in a Pentaho JavaScript JSON by matching keys to merge with an existing JSON document

My goal is to construct a Json document by breaking it down into smaller pieces, with each piece containing the necessary keys to insert the smaller Json bits into the correct json structure. As I am relatively new to JavaScript and still in the process of ...

Is there a way to keep my <nav> positioned in the top right corner of my header?

I'm in the process of setting up a fresh homepage and I've implemented the code below: menu { width: 100%; height: 60px; background: rgb(0, 0, 0); z-index: 2; position: fixed; } #content { margin: 0 auto; width: 1024px; height: ...

Verifying that the data has been successfully saved using JavaScript

When a user submits a small chunk of data via AJAX using a standard update action and a remote form, the information is sent to the action as javascript. The response is then rendered in javascript utilizing format.js. def update @message = Message.wher ...

Using JQuery template: a guide to accessing recently added option elements with JQuery templates

I have a JSON array that needs to be iterated through in order to create HTML option items using the JQuery template. However, I am facing an issue where there are duplicate values within each group of data. For example, 'a' can appear in both gr ...

Issue with ng-multiselect-dropdown where clearing selected items programmatically does not visually work as expected

Utilizing the ng-multiselect-dropdown, I have encountered an issue where deselecting an option within the object itself clears the selected items visually and in the variable array. However, when programmatically clearing the selectedItems, the variable a ...

New to using JavaScript and JQuery, attempting to position a form underneath an image at a specific URL for the

Hello, I'm having difficulties placing a form below an image with a specific URL. As someone who is still learning JQuery, I am unsure of what mistake I might be making. Is there anyone who can help me figure out what's wrong here? <html> ...