Interactive sliding sidebar menu using jQuery - Connect link buttons to individual slides without needing to duplicate functions for each link

Check out this sidebar menu created using JSFiddle: https://jsfiddle.net/jvp2h1am/.

I need help simplifying my JavaScript code to display the submenu for the clicked button without creating separate functions for each button.

Additionally, I want to implement a feature where clicking on one button closes the currently open submenu. For example, if the Personal menu is open and Business button is clicked, the Personal menu should close within the same function.

Here's the HTML structure:

<div id="sidebarPrimary">
    <ul id="sidebarPrimaryNav">
        <li class="navButton"><a href="#" target="blank_">JA</a></li>
        <li id="homeButton" class="navButton active"><a href="#">
            <div class="navButtonContent">
                <span class="fa fa-lg fa-home"></span>Home
            </div>
        </a></li>
        ... (other menu items)
    </ul>
</div>

... (other submenu elements)

The JavaScript logic:

$(document).ready(function() {
    
    $('#personalButton').click(function() {
        $('#personalMenu').toggleClass('open');
    });

    $('#businessButton').click(function() {
        $('#businessMenu').toggleClass('open');
    });

    ... (repeat for other buttons)

});

Answer №1

$(document).ready(function() {
    
    $('.navButton').click(function() {
        
        $('#'+$(this).attr('show-id')).toggleClass('open');
        
    });
   
})
/* 
COLOUR PALETTE 
sidebar primary background: #2F323E;
sidebar secondary background: #262A34;
page primary background: #fff;
...
                        <span class="fa fa-lg fa-list"></span>Payslips
                    
                    </div>
                    
                </a></li>
                
            </ul>
            
        </div>
        
        <main>
            
            <div id="topnav">
              
                <div id="topnavLeft">
                    
                    <a class="button" href="#"><span class="fa fa-plus"></span>New Invoice</a>
                    
                </div>
                
                <ul>
                    
                    <li class="navButton"><a href="#"><span class="fa fa-lg fa-sign-out"></span></a></li>
                    
                    <li class="navButton"><a href="#"><span class="fa fa-lg fa-question"></span></a></li>
                    
                    <li class="navButton"><a href="#"><span class="fa fa-lg fa-cog"></span></a></li>
                    
                </ul>
                
            </div>
            
            <div id="mainContent">
                
                
                
            </div>
            
        </main>
   
    </body>

Please check the code. So instead of unique IDs for each button, I have used a common class and passed an attribute called show-id with the ID of the list you want to show.

Thanks, I hope this explanation helps!

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

Encountering the "potential null object" TypeScript issue when utilizing template ref data in Vue

Currently, I am trying to make modifications to the CSS rules of an <h1> element with a reference ref="header". However, I have encountered a TypeScript error that is preventing me from doing so. const header = ref<HTMLElement | null> ...

What is the best way to insert text into a paragraph tag using JQuery?

As part of my learning journey on Codecademy, I decided to challenge myself by creating my very first Chrome extension using HTML/CSS, jQuery, and Javascript. My initial goal is to learn how to append text to a paragraph tag when a button is clicked. Here ...

Adding data to an array using jQuery

I have a list of items called data and an empty array called quotations: var data = {}; var quotations = []; My goal is to populate the quotations array with data values. Each time I add new data, it is successfully added, but all data values end u ...

Modifying the HTML <select> element with JavaScript

[resolved] I'm encountering an issue with the code below that is supposed to dynamically change the options in a second drop-down menu based on the selection made in the first menu. I've tried to troubleshoot the problem but haven't been suc ...

Executing a Javascript button click in Selenium without an ID using Java

Currently, I am in the process of setting up a Java program integrated with Selenium automation tool. Upon the initiation of the program, a Chrome extension that is crucial for its functionality loads alongside the Chrome browser instance. Following this ...

Best method for reverting react-native to previous version

Here's the dilemma I'm facing: I had a functional version of a react-native project that was running smoothly and committed to my git repository. Deciding to upgrade from react-native 0.26.3 to 0.28 led me into a tangled web of dependencies, so ...

Ensuring text is perfectly centered within a div, regardless of its length

In the quest to center text of unknown length within a div, challenges arise. Constraints limit its size to a certain extent, making it unclear whether one or two lines will be needed. As such, traditional methods like line-height are not viable options. A ...

JSON script and datetime formatting procedures

Here is my PHP/JSON script from localhost: If you need to download the PHP files to edit them in your answers, you can find them here. The link to the JSON file is mentioned in large-schedule.js. Instructions on usage are provided. The script partially w ...

The reactivity of vuex state seems to be lacking

Implementing a loading spinner condition using Vuex to manage loading = true/false across multiple components. LoadingSpinner.vue <template> <fulfilling-square-spinner v-show="loading" class="loading-spinner" :animation-duration="4 ...

Is it possible to detect when a scrollable div is "in focus" on Firefox?

When using Firefox, a scrollable div can become "focused" and respond to mousewheel and Page Up/Down keys, although technically divs cannot be focused according to the HTML5 specification. This means that even though events are triggered on the div, it is ...

Node.js, Express continues to execute an if statement even if the condition is false

My goal is to determine whether the user signed in is an admin or not. User data is structured like this: [ { "isAdmin": "true", "_id": "60c6df22f25d381e78ab5f31", "name": "Admin", ...

Best practices for updating nested properties in Angular objects

I have a dataset that includes information about fruit prices for different years: { "fruits": [ { "name": "apple", "prices": [ { "2015": 2, "2014": 3, ...

Create identical buttons using Bootstrap 4

I am trying to create uniform left and right buttons, but I am facing issues with making them look the same on both PC and mobile devices. Here is the current appearance: View the current button design <h3> <a href="" ...

What is the best way to showcase my background image using html and css?

I've come across a similar topic addressing my problem, but I am still unable to resolve it. I am attempting to add a background image to my portfolio, but for some reason, it is not working. Can anyone offer any suggestions or ideas? Here is the cod ...

Python Qt - Unlocking the Power of QTextDocument and QPainter in the Toolbox

I am looking to create a comprehensive report using a toolbox that includes multiple documents. Starting with two pages is ideal as I work on formatting later. In my attempts, I have tried utilizing QTextDocument in Html and alternatively QPainter for thi ...

KineticJS: Issue with JSON saving - Objects are being duplicated during the save process

Major Revision After assessing my current situation, it appears to be another puzzle or scenario, specifically related to saving to json in a broader context. To illustrate, I include a new Shapegroup to a layer on the stage by utilizing the following co ...

CKeditor does not accept special characters or diacritics in keywords

Recently, I came across a helpful code snippet for CKeditor that counts and ranks the most used words in a textarea. This feature is invaluable for generating SEO-keywords suggestions while writing articles. However, there is an issue with non-English char ...

Will my variables become unbound when a new object is created?

Currently, I am developing a component within my Angular application where I am binding an object: CustomComponent.js angular.module("app").component( "customComponent", { controller: function() { var ctrl = this; ctrl.createInstance ...

What is the importance of setting up openTelemetry before any other code runs?

If you're using the OpenTelemetry SDK for Node.js, it's important to set up tracing before running any other code. This can be found in detail in the official documentation. However, I tried to ignore this recommendation and noticed that no trace ...

Opposing the Return Value of a Callback Function

Question to ponder: Is it possible to invert a callback function that results in either true or false when using it with an array.filter() statement? For example: //the callback function function isEven(element, index, array){ if (index%2 == 0 || ind ...