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

Here's a guide on customizing the appearance of the date picker in NativeBase components for React Native by

Is there a way to show icons while using the date picker component from the Native Base UI library? ...

Attempting to transfer information from a JSON file to a Netflix-inspired platform

Images I am currently working on integrating data from my json file export const products = [ { name: 'iPhone 11', image: '/assets/images (7).jpeg', time: '1 hour 14mins', age: '+16&apo ...

Are there any plugins available for creating a progress bar using jQuery?

Looking for a Progress Bar jQuery Plugin Is there a jQuery plugin available that can dynamically adjust the length of a progress bar depending on a number input? Ideally, as the number decreases, the progress bar should also become shorter and vice versa. ...

What is the reason behind Chrome Dev Tools not automatically adding the parentheses when a method is selected?

In the console of Dev Tools, if you have an object named x with three methods/functions - a(), b(), and c(i, j, k), why doesn't it automatically insert the parentheses, along with the correct spaces for the parameters (similar to eclipse for Java) whe ...

Tap on the child to reveal their parent

I am working with a family tree that includes dropdown menus containing the names of parents and children. Each child has a link, and when I click on a child's link, I want their father to be displayed in the dropdown menu as the selected option. Can ...

Using jquery to transition an image to fade out and then reappear in a different position

There is an image in a div with the highest z-index. Upon clicking on something, the image should fade out and then fade in at a specified position below another image with the class "aaa". The current approach involves using jQuery to fade out the image ...

What is the best way to modify JSON data within a file?

To start, I retrieve a JSON array by using the following JavaScript code: $.getJSON("myJSONfile.json") .done(function(data) { myData = data; }); After storing the data in myData, which is a global variable, I proceed to add more informati ...

Guidelines on executing a function after page load in meteor

Currently, I am using cursor.observeChanges to monitor new records inserted in MongoDB and trigger a notification when that happens. The issue I am facing is that these notifications are popping up when my app is loaded for the first time or when I navigat ...

Steps to retrieve the latest value of a specific cell within the Material UI Data Grid

After updating the cell within the data grid, I encountered an issue where I could retrieve the ID and field using the prop selectedCellParams, but retrieving the modified value was proving to be challenging. In order to successfully execute the PUT reque ...

Perform DOM manipulation prior to triggering the AJAX event to prevent CSRF Error

Currently, I am faced with a challenge while working on Django. My goal is to implement a chained AJAX call - meaning that once one call returns, it triggers additional AJAX calls. Despite thorough research and referencing the suggested methods in the Djan ...

What is the process for altering an SVG image following a click event in Javascript?

I have a tab within a div that includes text and an svg icon as shown herehttps://i.stack.imgur.com/TjwIK.png When I click on the tab, it expands like this https://i.stack.imgur.com/XNuBi.png After expanding, I want the svg icon to change to something e ...

Tips on automatically focusing on an input within a Semantic UI React dropdown

I'm attempting to automatically focus on an input located within a Semantic UI React dropdown by using a ref, but unfortunately, it's not functioning as expected. The input should be focused when the dropdown is opened. Check out the code sandbox ...

Ways to release a client-side script with npm?

Within my nodejs package, I have included code that can be executed on both the backend and in a single .js file for browsers. In order to utilize the browser script, it must be placed within a script element in an HTML file. My query pertains to whether t ...

Assistance with utilizing the jQuery .html() function

Presently, I am executing the following code snippet: <script type="text/javascript"> $(function(){ $("#ipad").submit(function() { $.post("ipadcheck.php", $("#ipad").serialize(), function(data) { if(data.error == 'TRUE& ...

What is the best approach to updating multiple rows instead of just the first row using the update button located on both sides using PHP and AJAX?

Starting fresh, so I might sound like a beginner with this question. How can I make use of the update button to update specific rows instead of just the top row? Every time I try to update, it only works for the top row. Here's the code snippet from ...

How to Eliminate Image Flickering While Loading in a React Component

Currently, I am developing a React component that takes an imageUrl and displays it on a canvas with a deliberate 2-second delay to mimic loading time for larger images. However, I have encountered a problem: when the imageUrl changes in the parent compone ...

What are some strategies for accessing the original values of form components that have not been altered when using ngModel?

I am currently developing a form and I intend to utilize the previous values as "value" in the form. By employing ngModel dynamically, I am able to change some properties. However, I have encountered an issue where the field that remains unchanged by the u ...

Creating a render function that includes the img.src parameter requires careful thought and consideration

I am currently working on a dilemma where I need to dynamically adjust the height and width of an image in my render() function every time there is a state change. Here is the code snippet: render() { const imageURL = photos[this.state.currentImage]. ...

Is there a way to use JavaScript to import several custom fonts at once?

Is there a way to import a long list of custom fonts as icons using Javascript? I have been obtaining the font list from an API, but importing them one by one with pure CSS using @font-face is time-consuming and difficult to maintain. @font-face { fon ...

"Implementing a click event handler on a button within an iframe

On my website, I have embedded an iframe containing external content. Within the code of this iframe is a button identified by the id "XYZ." I want to create an onclick function for this button. Here's what I've attempted: $( "#XYZ" ).click(fun ...