Jquery for controlling the navigation menu

I'm new to JavaScript and facing 3 challenges:

1. When I click on the parent <li>, the correct content of the child <sub> does not show up. Each category like "colors, shapes, sizes" should have corresponding child categories like "green, circle, large"; but when I click on the <li>, "large" content appears for all <sub> tags. How can I display the correct content when clicking on a specific <li>?

2. Currently, my code only hides the previous click's content when I click the same <li> again. I want to hide the display of the <li> not only on its second click, but also when I click on a different <li> while displaying the newly clicked <li>'s content simultaneously.

3. I'm attempting to smoothly transition (slide) the <sub> content from behind the <ul>. I have tried using the "transition" property, but it's not working as intended; when I click on an <li>, the <sub> just appears, but I want it to slide out.

Check out the JS Fiddle here: https://jsfiddle.net/6sapmodc/2/

HTML

<blue>
  <ul>
    <li>Colors
      <sub>Green</sub>
    </li>
    <li>Shapes
      <sub>Circle</sub>
    </li>
    <li>Sizes
      <sub>Large</sub>
    </li>
  </ul>
</blue>

CSS

blue {
    float: left;
    background-color: orange;
    height: 80px;
    position: absolute;
    z-index: initial;
}

blue ul {
    list-style: none;
    background-color: gray;
    position: absolute;
    z-index: 5;
    display: flex;
    align-items: center;
    justify-content: center;
    z-index: 5;
}

blue ul li {
    height: 60px;
    width: 60px;
    background-color: red;
    text-align: center;
    line-height: 60px;
}

blue ul li:hover {
    cursor: pointer;
}

blue ul li sub {
    position: absolute;
    background-color: pink;
    width: 300px;
    height: 50px;
    z-index: -4;
    top: 0;
    display: none;
}

Jquery

$(document).ready(function()
{
    $("li").click(function()
    {
        $("sub").toggle();
    });
});

Answer №1

1) In order to reference the clicked <li> element, you should utilize $(this) and then use find("sub") to access the corresponding <sub> child.

2) and 3) Involve detecting the current visible <sub> element, sliding it out with toggle("slide"), and then displaying the related <sub> of the clicked <li> element.

Take a look at the following example:

$(document).ready(function()
{
   $("li").click(function()
   {
       var clickedSub = $(this).find("sub");

       // If there are no visible sub elements,
       // then just show the clicked one.
       
       if ($("sub:visible").length == 0 || clickedSub.is(":visible"))
       {
           clickedSub.toggle("slide");
           return;
       }
       
       // Otherwise, first hide the current visible element,
       // and then show the sub of the clicked element.
       
       $("sub:visible").toggle("slide").queue(function()
       {
           clickedSub.toggle("slide");
           $(this).dequeue();
       });
   });
 
});
blue {
    float: left;
    background-color: orange;
    height: 80px;
    position: absolute;
    z-index: initial;
}
blue ul {
    list-style: none;
    background-color: gray;
    position: absolute;
    z-index: 5;
    display: flex;
    align-items: center;
    justify-content: center;
    z-index: 5;
}
blue ul li {
    height: 60px;
    width: 60px;
    background-color: red;
    text-align: center;
    line-height: 60px;
}
blue ul li:hover {
    cursor: pointer;
}
blue ul li sub {
    position: absolute;
    background-color: pink;
    width: 300px;
    height: 50px;
    z-index: -4;
    left: 180px;
    top: 0;
    display: none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<blue>
    <ul>
        <li>Colors
          <sub>Green</sub>
        </li>
        <li>Shapes
          <sub>Circle</sub>
        </li>
        <li>Sizes
          <sub>Large</sub>
        </li>
    </ul>
</blue>

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

The request has been unsuccessful with error code 405 in Nextjs version 14

I am currently working with NextJs version 14 and encountering a 405 error: GET http://localhost:3000/api/products 405 (Method Not Allowed) Uncaught (in promise) AxiosError products.js "use client" import { useState } from 'react'; ...

Error: The function jQuery(...).hexColorPicker does not exist

I am attempting to utilize a color-picker jQuery plugin. Below is a screenshot of the JavaScript file: https://i.stack.imgur.com/ovRjx.png Here is the code I am using to initialize it: <script type="text/javascript> jQuery(function(){ ...

Learn how to implement a forced download feature in Symfony2 when using an Ajax call that returns JSON

I'm currently working on creating a download link for a file in Symfony2. While the file does download successfully, I've encountered an issue specifically in Chrome where it doesn't seem to work properly. I'm unsure of how to resolve ...

When using NodeJS, having multiple 'if' statements may result in conflicting headers being returned,

Introduction to Promises. Encountering challenges in NodeJS due to the utilization of multiple if-statements and return-statements. Considering leveraging Promise as a potential solution. This snippet showcases an example: const express = require(' ...

Tips for utilizing the <base> element in HTML5 for selective anchor tags

I only have one base tag in the head section of my HTML document, and there are two anchor tags with different URLs as shown below: <!DOCTYPE html> <html lang="en"> <head> <base href="https://www.youtube.com"/> </head> &l ...

Delivering static HTML content on Google App Engine using Python

I'm struggling to load static .html pages for my Python application. Every time I try to access a link like index.html, the page remains blank and the server log shows a 404 error. This issue persists with other static .html files such as about.html. ...

Using javascript to overlay and position many images over another image

I've searched extensively but haven't been able to find any relevant answers here. Currently, I am developing a hockey scoring chance tracker. My goal is to display an image of the hockey ice where users can click to mark their input. Each click ...

Utilizing the CSS :not() selector within a nested table

I am having an issue with my AjaxControlToolkit where the main-page CSS is affecting the inner "calendar" popup. To illustrate what I need, what I've tried, and the temporary workaround, I have simplified everything into a one-page example. I am in s ...

When you click on the column header to sort, the corresponding column row changes color in JavaScript

https://i.sstatic.net/4ELuv.jpg When a user clicks on a column to sort, the color of the column changes or highlights the row. In my tablesorter with ascending and descending sorting capabilities, I want the sorted column to change colors for better visib ...

How can you use jQuery to target a textbox based on its value that includes quotation marks?

Dealing with a JavaScript string that includes a quote mark can cause some difficulties. For example, strings like Don't click this checkbox or He said "hi" pose unique challenges when trying to find an exact match in a checkbox value. Consider the H ...

Guide to building a React project with an outdated edition of Create React App

Currently, I'm following an older tutorial to learn React, and as a result, I need to set up a project using Create React App version 1.5.2. I successfully installed <a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="204352454 ...

Centering loaders within elements of an unordered list

I am working on a navbar that uses Bootstrap 3 and AngularJS. Within this navbar, I have an unordered list with li elements. Below is a snippet of my navbar: https://i.stack.imgur.com/o75Lp.png This is the code for my navbar: <div class="navbar-head ...

Experiencing difficulty incorporating JSON and JS into jQueryhandleRequestJSON and JS integration with jQuery

I'm having trouble fetching the 'sigla' field from a JSON file and inserting it into an HTML 'option object'. I could use some assistance with this issue, so if anyone out there can lend a hand, it would be much appreciated! Here ...

Reliable drop-down box is not functioning properly

I am new to AJAX and I came across a solution for my issue on this page, but I am having trouble getting it to work. I want the input #precio to change when I select an option in the select #producto. This is the code I have: <form action="actualizar ...

Ensure a button is automatically highlighted within an active class script

I have created a set of buttons that allow users to change the font family of the text. I would like the border and text color to update automatically when a specific option is selected. Currently, the JavaScript code works well, but when the page first l ...

Guide to deploying a Node.js application with a Gruntfile on Heroku

I have encountered an issue while trying to deploy my Node.js application to Heroku using the BUILDPACK_URL. Despite searching for a solution, I have been unable to find a suitable answer. Here is the procedure that I followed: heroku create myapp hero ...

How can I incorporate dynamic moving lines into my website's loading sequence?

Link to Gyazo image 1: https://gyazo.com/015425f0decb187e28b620c1e3206391 Issue with first image: https://gyazo.com/dfcd33e8a4fd5bea64e51fe40556f0bf I'm currently working on a website and came up with a cool concept of having two lines crossing the s ...

Is it possible to load a JavaScript file from a different domain using a bookmarklet?

I'm a newcomer to bookmarklets and I am experimenting with loading a JavaScript file from my own server/domain using the following bookmarklet/javascript code: javascript:(function(){s=document.createElement('script'); s.type=' ...

Caught off guard by this promise: TypeError - Attempting to access a property that does not exist in my Ionic 2 application

I'm encountering an issue with native Facebook login that displays the following error message: Uncaught (in promise): TypeError: Cannot read property 'apply' of undefined https://i.sstatic.net/PDWze.jpg I have shared my entire project ...

Unable to locate and interact with a specific element within a dropdown menu while utilizing Protractor

I am currently facing an issue with selecting a checkbox from a dropdown in jq widgets. The code seems to work fine when the element is visible on the screen, but fails otherwise. I have tried various methods such as executeScript and scrollIntoView to bri ...