What adjustments can I make to my jQuery code in order to animate the mobile menu when it is initially clicked?

I have been using the following mobile menu code for some time now and it has been working well. I have implemented a CSS animation so that when the menu button is clicked, it smoothly scrolls into view. However, I have noticed that the animation does not work on the very first click, but it works fine on subsequent clicks. If you notice any issues in my jQuery code, please feel free to point them out as I am still learning jQuery.

Any help or insights on what I might be overlooking to resolve this issue would be greatly appreciated.

jQuery(function() {
    // Display the menu when the button is clicked
    jQuery('#menu_btn').click(function() {
        if(jQuery('#menu').is(':visible')) {
            jQuery('#menu').animate({ left: '-100%' }, 'slow', function () {
                jQuery("#menu").css('display', 'none');
                jQuery('#menu_close').css('display', 'none');
            });
        } else {
            jQuery("#menu").css('display', 'block');
            jQuery('#menu').animate({ left: '0' }, 'slow', function(){
                jQuery('#menu_close').css('display', 'block');
            });
        }
    });

    // Close the menu when the X button is clicked
    jQuery('#menu_close').click(function() {
        jQuery('#menu').animate({ left: '-100%' }, 'slow', function () {
            jQuery("#menu").css('display', 'none');
        });
    });

    callOnResize();
});

jQuery(window).resize( function(){
    callOnResize();
});

function callOnResize() {
    var winwidth = jQuery(window).width();
    if (winwidth < 760) {
        jQuery( '#menu' ).css({ display: 'none' });
        jQuery('#menu').animate({ left: '0' }, 'slow');
    } else if (winwidth >= 760) {
        jQuery( '#menu' ).css({ display: 'block' });
    }
}

The HTML structure of the menu is very simple, using an unordered list (ul) output by WordPress:

<div id="menu">
<ul>
<li>item</li>
<li>item</li>
<li>item</li>
</ul>
</div>

Answer №1

Elements are considered visible if they occupy space in the document. Visible elements have a width or height greater than zero.

Your menu division "#menu" should be hidden by default with "display:none".

The code snippet should look something like:

jQuery('#menu_btn').click(function() {

        if(jQuery('#menu').is(':hidden')) {
            jQuery("#menu").css('display', 'block');
            jQuery('#menu').animate({ left: '0' }, 'slow', function(){
               jQuery('#menu_close').css('display', 'block');
            });
     });

        } else {

            jQuery('#menu').animate({ left: '-100%' }, 'slow', function () {
                jQuery("#menu").css('display', 'none');
                jQuery('#menu_close').css('display', 'none'); 
        }
    });

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

Utilizing Ajax to retrieve an array of input textboxes and showcase the outcome within a div container

This is the form that I have designed for displaying information: <form name='foodlist' action='checkout' method='POST'> <table> <tr> <td>Product Name</td> <td>Price</t ...

What is preventing JSON.parse() from extracting the data from this json string in this particular scenario?

One of the challenges I'm currently facing involves extracting a specific item from a JSON-formatted string and displaying it on the screen using .innerHTML. The JSON string, named myData, is retrieved from a MySQL database via PHP. To achieve this, ...

GraphQL query must receive an object for the Mongo filter, but instead, it received a string

Is there a way to pass a filter option to MongoDB using GraphQL? I attempted to do it in a certain way, but encountered an error that stated: "message": "Parameter \"filter\" to find() must be an object, got {email: "<a href="/cdn-cgi/l/email ...

The AddClass function fails to function properly after an ajax form is submitted

I am facing a challenge in setting up validation for my ajax form. My goal is to have a red border appear around the input field if it is submitted empty. Unfortunately, when I try to use addClass(), it does not seem to have any effect. The alert message ...

Key within square brackets in a JSON array

I am dealing with a JSON array that includes a square bracket in the key, like this: { "msg":"OK", "data":[ { "nls!type":"NCR", "current":"Assign", "physicalid":"0FFE0001000009FC5BD6805C00001352", "attribute[custTitle]":"Tit ...

Experimenting with code within a window event listener function

I have a component in my AngularJS application that is functioning correctly. However, when it comes to test coverage, everything after the 'window.addEventListener('message',' part is not being covered. Should I create a mock object f ...

Is it possible to create a function that executes if a checkbox is checked, and another function if

When the radio button with the ID m1 is checked, my mesh updates its position. I attempted to make the mesh return to its original position if "#m1" is no longer checked. Is it necessary to trigger a function when checked and a different function when no ...

What is the method for defining a CSS property for the ::before pseudo element within an Angular component?

Can TypeScript variables be accessed in SCSS code within an Angular component? I am looking to achieve the following: <style type="text/css"> .source-status-{{ event.status.id }}::before { border-left: 20px solid {{ event.status.colo ...

Changing JavaScript functions into jQuery functions

Currently, I have this Javascript function that I am interested in converting to jQuery: function confirm() { var http = new XMLHttpRequest(); var url = "index.php?tag=' . $dt . '"; var params = "confirm_ref=' . urlencode(encry ...

Having trouble sending form data using the jQuery AJAX POST method?

I am facing an issue with a simple form that is supposed to send data to PHP via AJAX. However, when I submit the form, the data does not get sent across. Here is the JavaScript code: $(document).ready(function(e) { $('#update').submit(func ...

Tips for accessing the current state/value in a third-party event handler?

Consider the following scenario: function MapControl() { const [countries, setCountries] = useContext(CountriesContext) useEffect( () => { ThirdPartyApi.OnSelectCountry((country) => { setCountries([...countries, country]) }) }) ...

Generate interactive tables using data from an XML file

Hello, I'm in the process of generating tables from an XML file using Node.js with the Express framework. I am utilizing npm modules xmldom and xmldoc for this task. The objective is to present these data tables on an ejs page. Here is the structure ...

Roll high with the combinations of Yahtzee

<body> <div class="board" style="border: 2px solid black"> <table border="1" height='200' > <tr> <th colspan="3">Upper Section</th> </tr> <tr> <td>Aces</td> <td>Sum of ...

What is the best way to combine text with a PayPal field variable?

We recently encountered an issue with our standard PayPal Form implementation for online payments. Our form includes a field for customers to input a pickup date/time, using the passthrough variable "invoice" as recommended in the PayPal Docs. Everything w ...

Looking to spice up your static HTML site? Dive into the world of Ruby on

I recently developed an app that features a static HTML webpage containing text and images, and now I'm interested in incorporating Ruby on Rails to explore its capabilities further. After creating a basic RoR application, I copied the HTML content f ...

PhantomJS encountered a TypeError when trying to access a non-existent object during the evaluation of 'document.getElementById()'

Recently, I delved into the world of PhantomJS and its ability to extract data from websites through JavaScript. This process is commonly referred to as web scraping. My goal was to retrieve the text content of an element by its ID. However, I encountered ...

Utilizing Angular to automatically extract keys from nested objects in a response

In my Angular application, I am facing a challenge with accessing nested responses from the server. The data structure contains multiple responses within one parent object, and I am struggling to dig deeper into it. Here is the code snippet I have so far: ...

A step-by-step guide on bringing in objects in JavaScript and Node.js

Let's say we have a file called main2.js exports.obj = { x: 10, setX: function(y) { this.x = y; }, getX: function() { return this.x; } }; Now, we also have two other files: abc.js const obj = require("./main2").o ...

Why isn't my AJAX POST request to PHP functioning correctly?

It was all working perfectly fine earlier, but now something seems off and I must have made a mistake somewhere. I'm in the process of setting up a form where the information entered is sent via AJAX to my PHP file, which then outputs the username an ...

The JavaScript filter function will only return arrays that have matching IDs

How can I filter out book data based on the author's id? I have a list of books with various author ids, and I want to only return the books that match a specific author id. However, my current filtering method doesn't seem to work correctly as i ...