Choosing various li classes within a navigation bar

Struggling to pick the right JQuery elements for my portfolio site. The aim is to show/hide the .inner (Task) items by clicking on the .outer (Category) items, complete with rotating .arrows when the menu expands.

Check out a similar question, along with this jsfiddle.

Kudos to Tats_innit for the initial response.

The HTML looks like this:

<li class="outer" hook="01">
    <div class="arrow"></div>
    Category 1
</li>
<li class="inner" id="menu-01">
    Task 1
</li>
<li class="inner" id="menu-01">
    Task 2
</li>
<li class="inner" id="menu-01">
    Task 3
</li>

<li class="outer" hook="02">
    <div class="arrow"></div>
    Category 2
</li>
<li class="inner" id="menu-02">
    Task 1
</li>
    <li class="inner" id="menu-02">
    Task 2
</li>
    <li class="inner" id="menu-02">
    Task 3
</li>

And here's the jquery code:

$(document).ready(function(){
        $('.outer').click(function(){
            var elem = $('#menu-'+$(this).attr('hook')),
                arrow = $(this).children('.arrow')

            if (!elem.is(':visible'))  {
                arrow.rotate({animateTo:90, duration:128});
            } else {
                arrow.rotate({animateTo:0, duration:128});
            }
            elem.slideToggle('128ms', function() {
            });

        return false;
    });
});

I'm aware that I need to modify

var elem = $('#menu-'+$(this).attr('hook'))
but unsure how to display all instances of .inner. I opted not to nest the .inner elements due to having a hover state background-color: #f1f1f1; for the .outer class.

Answer №1

The approach you have taken to solving this problem needs some adjustment. It is important to address the issues with your current approach before moving on to finding a solution.

  1. Ensure unique use of the id attribute. Having multiple elements with the same id in a single page can cause problems; consider using class instead.
  2. hook is not a recognized HTML attribute; it may be beneficial to standardize it as data-hook for better compatibility and usability. Refer to this resource for more information.
  3. Nesting the .inner within the .outer element is recommended for semantic clarity and accessibility. This organization structure can also help resolve issues such as background hover effects with proper CSS implementation.

By utilizing nesting, you may find that many of the unnecessary ids, classes, and data attributes can be eliminated unless specifically required for other functionalities apart from list display.

Following these adjustments, your updated HTML will resemble the example below:

<ul>
    <li class="outer">
         <div class="arrow"></div>
         Category 1
         <ul>
             <li>
                 Task 1
             </li>
             <li>
                 Task 2
             </li>
             <li>
                 Task 3
             </li>
         </ul>
    </li>
    <li class="outer">
         <div class="arrow"></div>
         Category 1
         <ul>
             <li>
                 Task 1
             </li>
             <li>
                 Task 2
             </li>
             <li>
                 Task 3
             </li>
         </ul>
    </li>
</ul>

For handling interactions with jQuery, apply the following code:

$('.outer').click(function(){
    var elem  = $(this).children('ul'),
        arrow = $(this).children('.arrow')

    if (!elem.is(':visible'))  {
        arrow.rotate({animateTo:90, duration:128});
    } else {
        arrow.rotate({animateTo:0, duration:128});
    }
    elem.slideToggle('128ms', function() {
    });

    return false;
});

To enhance the semantics, consider replacing the .arrow element with a CSS3 pseudo-element applied to the li.outer for a cleaner design and improved functionality.

Edit

If you encounter difficulties implementing the suggestions provided, feel free to refer back to this guidance. A working example demonstrating the proposed changes has been prepared based on the advice shared here. You can view the demonstration by accessing the link below:

Working example

Answer №2

If you want to organize a group of elements with the classes outer and inner inside a container div

<div>
    <li class="outer">
        <div class="arrow"></div>
        Category 1
    </li>
    <li class="inner">
        Task 1
    </li>
    <li class="inner">
        Task 2
    </li>
    <li class="inner">
        Task 3
    </li>
</div>

then your javascript code will look like this

$('.outer').click(function(){
    var elem = $(this).siblings('.inner'),
        arrow = $(this).children('.arrow')

    if (!elem.is(':visible'))  {
        arrow.rotate({animateTo:90, duration:128});
    } else {
        arrow.rotate({animateTo:0, duration:128});
    }
    elem.slideToggle('128ms', function() {
    });

    return false;
});

this won't change the background-color of the outer class in the meantime

Answer №3

<script>
$(document).ready(function(){
    $('li.inner').hide();
    $('.outer').click(function()
    {
        var elem = $(this).attr('hook');
        $('li.inner').hide();
        $(".menu-"+elem).toggle();
    });
});
</script>
<ul>
<li class="outer" hook="01">
<div class="arrow"></div>
Category 1
</li>
<li class="inner menu-01">
Task 1
</li>
<li class="inner menu-01">
Task 2
</li>
<li class="inner menu-01">
Task 3
</li>

<li class="outer" hook="02">
<div class="arrow"></div>
Category 2
</li>
<li class="inner menu-02">
Task 1
</li>
<li class="inner menu-02">
Task 2
</li>
<li class="inner menu-02">
Task 3
</li>
</ul>

Initially, ensure to modify the li identifiers to classes as two li elements should not share the same ID.

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

Ways to eliminate the final empty space in a grid

Looking to create a layout with 5 boxes? Currently, I have managed to set up the grid structure, but the issue is that there is still some space below the last item in the grid. Below is the styled component for Container: const Container = styled('di ...

Unexpected results are occurring with the margin merging process

Struggling to create a layout for a website, here is the CSS and HTML I am using. Issue: 1. The header and navigation divs seem to be merging even without using margin 2. The merge is not happening between the navigation and left-nav/content divs Can an ...

utilizing geographical coordinates in a separate function

I have a program that enables users to access the locations of communication cabinets. I am attempting to utilize html5 to transmit latitude and longitude information to a php script (geo.php) in order to update the database record with map coordinates. Ho ...

By utilizing the HTML element ID to retrieve the input value, it is possible that the object in Typescript may be null

When coding a login feature with next.js, I encountered an issue: import type { NextPage } from 'next' import Head from 'next/head' import styles from '../styles/Home.module.css' import Router from 'nex ...

Expanding Module Scope to Just the Request (employing Require, Node.js)

Original Query The project I am currently working on is using Express to manage HTTP requests. The structure of the project is quite intricate, with multiple embedded require statements. Our main challenge lies in maintaining access to the request and re ...

Change the behavior of an onclick event on the second click

I'm trying to make a button on my website that not only plays music when clicked but also changes the text inside the button to "Go to SoundCloud" and redirects to SoundCloud. Currently, I have been able to achieve both functions separately - redirect ...

ng-bind-html is having trouble parsing the HTML correctly and binding it

Here is the code for my controller: myApp.controller('actionEditController', ['$scope', '$stateParams', '$sce',function ($scope, $stateParams, $sce) { $scope.table="<p>OOPSY</p>"; $sc ...

Using jQuery to define active or hover background images

I'm currently working on a list containing 5 items, with the first one active by default (thanks to jQuery adding a 'active' class). Each item has its own background image. When I click on any of the list items, another div gets updated with ...

The package.json file engines field specifying the version with a tilde and then a greater than sign (~>)

When a package.json file includes an engines field such as this: "engines" : { "node" : "~>12" }, What is the significance of ~> in this context? ...

Simple Authentication in Node.js with Express Sessions

Scenario - After successfully creating a basic website using Node.js, the next step is to implement a simple form of local authentication to ensure that only authorized users have access to the content. While researching various options like JSON Web Token ...

Vue.js: The Power of Manipulating Strings

Why is the filter method not working with this.userId, but it is working with the hard-coded value "admin"? How can I resolve this issue? computed: { UidMessages: function() { return this.Messages.filter(function(m) { return m ...

Error message in Angular when promises are not defined

Recently, I started working with promises for the first time. I have a function that returns a promise: public DatesGenerator(futercampaign: ICampaign, searchparam: any, i: number): ng.IPromise<any> { return this.$q((resolve, reject) => { ...

NodeJS executor fails to recognize Typescript's CommonJS Internal Modules

In the process of developing my NodeJS application, I am structuring it by creating internal modules to effectively manage my code logic. This allows me to reference these modules without specifying the full path every time. internal-module.ts export cla ...

Navigating through the CSS menu located in the main directory

I am facing an issue with accessing my CSS menu in different directories. In my root directory, I have a CSS menu that I want to use in subdirectories as well. However, when I navigate to a subdirectory, I find it difficult to go back to the main directory ...

Avoid showing duplicate values in the optgroup selection

Show the database value in the optgroup option. If the value of the parsing controller is equal to the option's value, do not display it within the HTML tag. Value of the parsing controller: {{$getData->status}} This is how my view blade looks: ...

Is there a way to eliminate the gap between two horizontal rule tags?

What causes the space between two <hr> tags to remain? Despite setting the width of the <hr> tags to 49%, there is still a gap between them. How can this space be removed from the <hr> tags? Shown below is the HTML and CSS code: *{mar ...

HTML and JQuery Image Slide Show

Help! I'm struggling with this image slider that's meant to showcase images fading in and out every 5 seconds. Being a beginner in coding, I could really use some assistance with getting it to work properly. Currently, I'm stuck on the firs ...

issue with node callback function - code malfunctioning

I have written a script in Node.js and Express to send an email after a SQL transaction is successfully completed! router.post('/',function(req,res,next){ sql.connect(config).then(function() { var request = new sql.Request(); ...

Encountering a DiscordAPIError[10062] when attempting to retrieve user points from the database due to an unknown interaction

content: "Congratulations, you have been successfully verified!", ephemeral: true, }); } } else if (interaction.customId === "giverole") { const userPoints = await findUser(interaction.member ...

React Material Design Cards for Responsive Layouts

Hi there, I am currently navigating my way through Material Design and attempting to ensure that the cards section is responsive by utilizing media queries and flex. However, I have encountered an issue where only a portion of the image is displayed when t ...