On a button click, the div's height will increase and then decrease when the same button is clicked again

I need help with a div that has its height set to 0px initially, and I want it to increase to 300px when a button is clicked. When the button is clicked again, I want the height to go back to 0px.

Here's the CSS code:

nav{
    height:0px;
    overflow:hidden;
    opacity:0;
}

And here's the JavaScript code:

$("#hamburger").click(function(){
            $('nav').stop().animate({ height: 300, opacity: 1 }, 'slow');
        },function(){
            $('nav').stop().animate({ height: 0, opacity: 0 }, 'slow');
    });

When I only use the first part of the JavaScript code, the animation works fine. But as soon as I add the second line, it doesn't work properly. I also tried using the toggle() function, but encountered issues where the height and opacity properties were not behaving as expected.

For more information, you can visit my website here.

If you have any ideas on how to fix this issue, I would greatly appreciate it. Thank you!

EDIT

Just a heads up, I am currently working on making my website responsive. The JavaScript code mentioned above is specifically for the mobile version. To see the result, please adjust your browser width to 480px or less.

Answer №1

Attempting to execute both functions simultaneously is causing a conflict. One function aims to increase the height of the div, while the other intends to decrease it.

Consider implementing the following approach instead:

$("#hamburger").click(function(){
    var maxHeight = 300;

    if(+$('nav').height() < maxHeight) {

        $('nav').stop().animate({ height: 300, opacity: 1 }, 'slow');

    } else if (+$('nav').height() === maxHeight) {

        $('nav').stop().animate({ height: 0, opacity: 0 }, 'slow');

    }
});

To streamline further, you could use this condensed version:

$("#hamburger").click(function(){
    var maxHeight = 300,
        nav = $('nav');

        nav.stop().animate({ height: +nav.height() < maxHeight ? 300 : 0, opacity: +nav.css('opacity') === 1 ? 0 : 1 }, 'slow');
});

By using the random + signs, any strings are automatically converted into numbers for increased efficiency.

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

Why does only one <h1> tag get added when clicked multiple times?

After implementing the code below to attach a handler to a button, I anticipated that each click would result in a new line of <h1> being added under the <p>. However, no matter how many times I click the button, only one <h1> is displa ...

After closing the box, make sure to hold it securely

After clicking the button and closing my box with jQuery (Toggle), I want the state of the box to be remembered after refreshing the page. If the box was closed, it should remain closed upon refresh, and if it was open, it should stay open. I am looking ...

Suggestions for creating a simple implementation of a 3 x 3 cell layout with a large center using flexbox are

Creating a grid layout like this 3 x 3 cell with large center using CSS Grid is quite straightforward. .container { display: grid; grid-template-columns: 60px 1fr 60px; grid-template-rows: 60px 1fr 60px; } But what if we wanted to achieve the same ...

Preset for Typescript in Babel 6

Can anyone help me find a Babel preset for Typescript that is compatible with Babel 6, rather than Babel 7? I've been searching for this module with no luck. Is it possible that the TS preset is not supported for Babel 6? ...

Issues arise with controlling access due to cache-control and canvas properties

I am attempting to utilize the browser canvas feature to manipulate images that are hosted on cloudfront. My goal is to configure cloudfront in a way that allows the browser to cache images with cache control set to max-age, while still enabling canvas edi ...

What is the best way to display an image in HTML?

I have successfully created an autocomplete search box that retrieves product names, but I am struggling to display the product photos. Here is the code snippet I am using: <asp:TextBox ID="txtContactsSearch" runat="server" Width="261"></asp:Text ...

Error occurs when using jQuery.ajax on mobile devices such as android or ios

When accessing my website, an ajax request is made to my REST API. It works perfectly on desktop browsers like Chrome, Internet Explorer, and Firefox, as well as on my Windows phone. However, when trying to access it from an Android or iOS device, the XHR ...

How can you ensure a line stays fixed to the bottom of a box regardless of the text size in SCSS and HTML?

I have a CSS rule that displays a line within a div only when the div is active. The specific SCSS class I am using is: .active-tab:after { content: ''; display: inline-block; height: 4px; width: 100px; right: -7px; background-color: ...

Transform an array of values into a new array with a set range

Looking for a solution in JavaScript! I currently have an array of values: var values = [3452,1234,200,783,77] I'm trying to map these values to a new array where they fall within the range of 10 to 90. var new_values = [12,48,67,78,90] Does anyo ...

Limit access to retrieve JSON data or execute PHP queries on the server

Currently, I am utilizing a JS library that necessitates passing JSON data to display information. To achieve this, I must parse the data using a PHP script, shown below: $.getJSON('http://example.com/q.php?a=3298&b=test', function(data)... ...

What is the appropriate way to retrieve an array that has been stored in the this.state property?

https://i.stack.imgur.com/y9huN.jpgAs a newcomer to react, I have been exploring the react documentation on making Ajax calls. While the docs make it seem simple to retrieve JSON information and set it to a state variable, I've encountered some challe ...

How do I deactivate dragControls in THREE.JS after enabling them for a group of elements?

My function currently activates dragControls when the "m" key is pressed, but for some reason, it doesn't deactivate when the key is released. How can I go about disabling the dragControls? I attempted to encapsulate the dragControls activation based ...

A guide on harnessing the power of the fetch API to retrieve data from an external

In the process of developing a fetchBill function, I have assigned the URL https://randomapi.com/api/006b08a801d82d0c9824dcfdfdfa3b3 to a variable named api. This function utilizes the browser's fetch function to send an HTTP request to the specified ...

Is there a way to retrieve documents from mongodb by querying for documents whose ids are stored within the array variable `ids` using the $in operator

Can someone help me with querying all documents based on IDs from an array passed to my code via user input? var attackersIds = fights[i].attackersIds; attackers = cardsCollection.find({"_id" : { "$oid" : { $in: attackersIds } } }); However, I encountere ...

"Exploring the best locations for storing CSS, JS, and image files in Spring

Having trouble figuring out where to place my public files. I attempted the solution mentioned in this thread on Stack Overflow but it didn't work for me. I've tried putting my public folder in various locations within the WEB-INF directory, but ...

Ways to retrieve the returned value from the JS FETCH API outside of its scope

As a beginner in Typescript React and the Ionic framework, I am trying to use the JS FETCH API to fetch data from a third-party source. However, I am struggling to access this fetched data outside of the fetch function. If anyone could provide some guidan ...

I'm sorry, but we were unable to locate the /bin/sh

After running a command using execSync that runs with sh, I observed the following: spawnSync /bin/sh ENOENT bin is now included in the PATH environment variable. Any ideas on this issue? ...

Accessing data in JSON format from a URL

I'm working on a website that analyzes data from the game Overwatch. There's this link () that, when visited, displays text in JSON format. Is there a way to use JavaScript to read this data and display it nicely within a <p> tag on my si ...

JavaScript - Changing the position of an item within a JSON object

I have implemented JQuery sortable to rearrange items in a JSON object into a JSON array. Let's assume we have the following JSON file: [ { "ID_id": "I3Y0RAmsr5", "DT_createdAt": "2020-12-02T14:39 ...

The android application experiences crashing issues when utilizing the position or zIndex style properties within a react-native environment

In my code, I am attempting to display a semi-transparent black screen over my page in order to show a message or prompt in the center. I have tried using zIndex or elevation with position:'fixed' or position:'obsolet', and it works per ...