How can you create an accordion menu that expands when a button is clicked?

Is there a way to make an accordion menu open when the 'More' button is clicked? I've tried, but it always starts in its expanded state and collapses when the button is clicked. What I really want is for the accordion to be closed initially and then open when the button is clicked.

Can someone please provide some guidance?

<input id="hide" value="+" src="./img/Mainpage-more-icon.png" type="button" /><br/>
<div id="rightMenu">
    <ul>
        <li>sss</li>
        <li>sss</li>
        <li>sss</li>
    </ul>
</div>
<script>
    $(document).ready(function() {
        $('#hide').click(
                function() {
                    //show its submenu
                    $("#rightMenu").stop().slideToggle(500);
                }
        );
    });
</script>

Answer №1

Include the following code snippet in your ready function:

$("#rightMenu").hide();

Alternatively, you can apply the CSS style display:none to achieve the same result.

Answer №3

Apply the CSS rule display:none to hide an element

<input id="hide" value="+" src="./img/Mainpage-more-icon.png" type="button" /><br/>
<div id="rightMenu" style="display:none;">
<!--------------------^-------^--------->   
    <ul>
        <li>sss</li>
        <li>sss</li>
        <li>sss</li>
    </ul>
</div>
<script>
    $(document).ready(function() {
    $('#hide').click(
            function() {
                //show its submenu
                $("#rightMenu").stop().slideToggle(500);
            }
       );
  });
</script>

FIDDLE

Alternatively, you can use jQuery to hide the element when the DOM is ready by using the hide() method

<input id="hide" value="+" src="./img/Mainpage-more-icon.png" type="button" /><br/>
<div id="rightMenu">
    <ul>
        <li>sss</li>
        <li>sss</li>
        <li>sss</li>
    </ul>
</div>
<script>
    $(document).ready(function() {
    $("#rightMenu").hide();
    $('#hide').click(
            function() {
                //show its submenu
                $("#rightMenu").stop().slideToggle(500);
            }
       );
  });
</script>

FIDDLE

Answer №4

Start by implementing the slideToggle function.

Take a look at this JSFiddle example

$('#rightMenu').stop().slideToggle(500);
$('#hide').click(
    function () {
        // Display the submenu
        $("#rightMenu").stop().slideToggle(500);    
    }
);

It's okay if you're not familiar with all of JQuery - basic knowledge can easily be found through Google.

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

An effective way to eliminate or verify duplicate dates within an array in AngularJS1 is by employing the push() and indexOf() methods

I have successfully pulled EPOCH dates and converted them into strings, but my previous code did not check or remove duplicates. Does anyone have any suggestions on what I can add to accomplish this? The timestamp in this case is the EPOCH date that I re ...

What is the best way to redirect users to the login page when they are logged out from a different tab or window?

Ensuring user authentication and managing inactivity are crucial components of my Nodejs application, where I leverage cookie-session and passport.js. app.use(require("cookie-session")({ secret:keys.session.secret, resave:false, saveUninitiali ...

Enable the parsing of special characters in Angular from a URL

Here is a URL with special characters: http://localhost:4200/auth/verify-checking/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="59663c34383035643230383d2b606a6e6b686d6e6e193e34383035773a3634">[email protected]</a> ...

Above the search box in jQuery Datatable's search box, there is search text displayed

My datatable looks like this: var exTable1 = $("#exTable").DataTable({ "language": { "search": "Filter", "searchPlaceholder": "search", "loadingRecords": "", }, data: datasrc "dom": '<"top"lf>rt<"botto ...

The backbone view is having trouble processing the data from this.model.toJSON()

I've been working on a Backbone code implementation to display all modifications before adding data to my model. However, every time I try to add something from my form, my view returns "this.model.toJSON() is not a function" and I can't figure o ...

Assist me in minimizing redundant code in a basic jQuery function

I successfully created a carousel using the jQuery cycle plugin with 4 links that correspond to different slides. Currently, I have separate blocks of code for each link, but I'm looking to optimize by creating a single function. $('#features-sl ...

Here are some steps for generating a non-integer random number that is not in the format of 1.2321312312

I am looking to create random numbers that are not integers, for example 2.45, 2.69, 4.52, with a maximum of two decimal places. Currently, the generated number includes many decimal places like 2.213123123123 but I would like it to be displayed as 2.21. ...

Is your Bootstrap input displaying the has-error class with a glyphicon, but the alignment is not vertically centered?

What is the reason for the misalignment of glyphicon-warning-sign form-control-feedback vertically in the code below after applying font-size: 20px; to the label? <div class="container"> <div class="content align-left contact"> ...

Exploring the possibilities with Node.js and OpenCV

I'm experiencing difficulties with face tracking and detection using the npm opencv package. Right now, I'm attempting to draw a circle around each detected face. Below are the error details and associated files. I'm unsure if it's a b ...

Tips for applying a CSS class with a smooth fade-out effect

In my Angular project, I am working on creating a custom notification component. Here is the template code I have so far: <aside *ngFor="let message of messages "> <div class="notification" style="position:fixed"> {{message.conten ...

Determine with jQuery whether the img src attribute is null

My HTML structure is as follows: <div class="previewWrapper" id="thumbPreview3"> <div class="previewContainer"> <img src="" class="photoPreview" data-width="" data-height=""><span>3</span> </div> </div> ...

Best practices for including jQuery in ASP.NET (or any other external JavaScript libraries)

Can you explain the distinctions among these three code samples below? Is there a preferred method over the others, and if so, why? 1.Page.ClientScript.RegisterClientScriptInclude(typeof(demo), "jQuery", Re ...

Importing multiple exports dynamically in Next.js

My current setup involves using a third-party package that I load dynamically in Next.js: const am5 = dynamic(() => import("@amcharts/amcharts5"), {ssr: false}) The imported amcharts5 consists of various exports and imports, such as: export { ...

Double the Power of jQuery Live Search with Two Implementations on a Single Website

I recently implemented a JQuery Live Search feature that is working perfectly. Here is the JQuery script: <script type="text/javascript"> $(document).ready(function(){ $('.search-box input[type="text"]').on("keyup input", function(){ ...

SMTPConnection._formatError experienced a connection timeout in Nodemailer

Our email server configuration using Nodemailer SMTP settings looked like this: host: example.host port: 25 pool: true maxConnections: 2 authMethod: 'PLAIN' auth: user: 'username' pass: 'pass' We encou ...

Is there a way to adjust the color of the checkbox?

After creating a show/hide toggle checkbox for a password input, I ran into an issue with changing the background color when it is checked. Our current code base includes a custom styled checkbox, but it lacks the ng-model needed for this particular featur ...

DOM is set for Jquery activation

I'm dealing with an issue in JQuery that I recently started working on. I have a large HTML page with a widget at the beginning, but when I use document.ready, it waits for the entire page to load before executing, which takes too long. Is there a wa ...

Table cell featuring a status menu created with Material UI DataGrid

I'm looking to include a column called "Filled Status." Although I've checked the documentation, I can't quite figure out how to do it. It seems like I may need to use renderCell when setting up the column, but I'm not sure how to make ...

Tips for creating multiple diagonal lines with CSS and HTML

Is there a way to create multiple diagonal lines within a rectangle using CSS and HTML from the start? I am interested in incorporating diagonal lines at the onset of the rectangle. Here is an example code that displays the rectangle: <div className={ ...

Troubleshooting: Laravel 5.6 Ajax Jquery Modal data submission issue in Database

As a beginner with Laravel 5.6 and using Ajax for CRUD operations in the Database, I am facing an issue with inserting data from my modal. Despite changing the default "id" to "asset_category_id" in the migration file and protecting it in the Model Class, ...