Show or hide a fixed position div using jQuery when clicked

I am new to jQuery and I am trying to create a "full page menu" on my own. However, I am struggling to hide the menu on the second click. I tried using .toggle() but I found out that it has been deprecated. Can someone assist me with this? Thank you so much and please excuse any mistakes in my English.

HTML

<div class="container">   
   <a id="bars" href="#">Open/Close Menu</a>
</div>

<nav id="nav" class="nav-default">
    <ul>
       <li>Home</li>
       <li>Services</li>
       <li>Portfolio</li>
       <li>Contact</li>
    </ul>
</nav>

CSS

#bars {
   position: fixed;
   z-index: 2;
}

#nav {
   position: absolute;
   width: 100%;
   height: 100%;
   text-align: center;
}

#nav ul {
   list-style: none;
}

.nav-default {
   left: -100%;
   top:0;
   background: #ccc;
}

jQuery

$(document).ready(function() {
   $("#bars").click(
       function (){
           $(".nav-default").animate({
               left: "0"
           }, 1000, function() {
               // Animation complete.
           });
       });    
}); 

Note: When I click the menu with this code, it only reveals!

Answer №1

The code for reset animation was missing, causing the animation to only move once. I added a check to reset the animation if the class "moved" exists. Take a look and let me know if you encounter any issues.

$("#bars").click(function (){
           var move;
           if(!$(".nav-default").hasClass('moved')){
               var move = 0;
               $(".nav-default").addClass('moved');
           }
           else{
                var move = "-100%";
                $(".nav-default").removeClass('moved');      
            }
             $(".nav-default").animate({
               left: move
           }, 1000);
 });

Fiddle

Answer №2

If you want to create a smooth transition for your menu, I suggest using CSS transitions along with adding a class to indicate when the menu is active.

You can check out the jsfiddle link for the code example: http://jsfiddle.net/975va7qv/

The HTML structure remains unchanged:

<div class="container">   
   <a id="bars" href="#">Toggle Menu</a>
</div>

<nav id="nav" class="nav-default">
    <ul>
       <li>Home</li>
       <li>Services</li>
       <li>Portfolio</li>
       <li>Contact</li>
    </ul>
</nav>

In the CSS section below, a new class is added for an open menu state, including a transition on the left property for a smoother effect.

#bars {
   position: fixed;
   z-index: 2;
}

#nav {
   position: absolute;
   width: 100%;
   height: 100%;
   text-align: center;
}

#nav ul {
   list-style: none;
}

.nav-default {
    left: -100%;
    top:0;
    background: #ccc;
    transition: left .5s ease;
}

.nav-default.is-open {
    left: 0
}

For JQuery implementation:

$(document).ready(function() {
    var nav = $('.nav-default'),
        bar = $('#bars');

    bar.click(function (){
        // Check if the nav is currently open
        if (nav.hasClass('is-open')) {
            // Close the nav
            nav.removeClass('is-open');
        } else {
            // Open the nav
            nav.addClass('is-open');
        }
    });    
});

Answer №3

Utilize a flag to control the animation.

var flag=0; //Initialize flag to 0
$(document).ready(function() {
   $("#bars").click(
       function (){
           if(flag==0) //Check the flag value
           $(".nav-default").animate({
               left: "0"
           }, 1000, function() {
               flag=1; 
           });
           else
               $(".nav-default").animate({
               left: "-100%"
           }, 1000, function() {
               flag=0;
           });
       });    
});

View the Fiddle here.

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

Applying CSS Styles to a Single Class Only

I have been using Zurb's Foundation to customize the navbar with my own styles, which has been successful so far. However, I encountered an issue with the responsive behavior of the navbar when the viewing container size changes. The navbar adds a sec ...

Why isn't the main body of CSS extending across the entire page?

I feel like I'm running headfirst into a wall trying to figure out why the code I wrote for this specific website isn't quite working properly. The main content area of my pages (the white space in the link below) is supposed to extend from the ...

Attaching Picture From Array To Vue

Is it possible for me to request assistance? I'm wondering how to bind an image to a vue component or more simply, how do you render an image from an array in vue? Allow me to share my code with you and explain in detail how I have approached this. W ...

What is the most effective method for exchanging variables between programs or threads?

I currently have a program that executes an algorithm processing real-time data. Once per hour, the algorithm's parameters are optimized based on new historical data. Currently, this optimization process is running in a single thread, pausing the rea ...

Encountered an error in Discord.js: Undefined properties unable to be read (execute)

Here is the code snippet from my main file: const { Client, IntentsBitField, Collection, intents, SlashCommandBuilder } = require('discord.js') const { TOKEN, PREFIX } = require('./config.json') const fs = require('fs'); const ...

Node and browser compatible JavaScript logging library for effective logging experience across platforms

Our team is utilizing Visionmedias debug library, as it seamlessly functions on both browsers and Node.js environments. We are in search of a more reliable alternative to debug that offers the same level of functionality (error, warn, info, etc) for both ...

Only one bootstrap collapse is visible at a time

Currently, I am using Bootstrap's collapse feature that displays content when clicking on a specific button. However, the issue I am facing is that multiple collapses can be open at the same time. I want to ensure that only one collapse is visible whi ...

Converting "require" to ES6 "import/export" syntax for Node modules

Looking to utilize the pokedex-promise for a pokemonapi, however, the documentation only provides examples on how to require it in vanilla JavaScript: npm install pokedex-promise-v2 --save var Pokedex = require('pokedex-promise-v2'); var P = new ...

displaying 'undefined' upon completion of iterating through a JSON file using $.each

For my project, I am attempting to extract only the date data from a JSON object. I have successfully looped through the object and displayed it, but the issue arises at the end of the loop where it shows undefined. I am not sure what mistake I am making. ...

Automatically complete a text box upon page initialization

My objective is to automatically populate three text boxes on page load by using the function initializeFormForDebugging(). Although I have successfully achieved this using the style section of my program, I am now required to call them within a function ...

Is there a way to configure my datepicker so that it displays only dates that are later than a specified date

At the heart of my inquiry lies a dilemma: I have two date pickers, one for leave_start and the other for leave_end. If an individual selects "YES" for a future text_field, I aim to ensure that the date pickers only display dates after the person's an ...

Testing Ajax code encounters error

Currently, I am running a code test with Jasmine and setting up a mock object for the ajax method. spyOn($,'ajax').and.callFake(function(e){ console.log("is hitting"); }) In order to test the code snippet below: $.ajax({ url: Ap ...

What is the process for creating two columns with an input box beneath them?

I am facing a challenge with my code. I am struggling to create the desired design where there are two columns and below them an input box that will be displayed when a button is pressed. The design I am aiming for can be viewed here: enter image descripti ...

Images are not displayed when utilizing font-awesome on a MVC 5 website

I'm having an issue where adding font-awesome to the style bundle is causing images not to display correctly. Instead of showing the right icon, I am getting a transparent box. My style bundle configuration looks like this: bundles.Add(new StyleBund ...

Sending a function as a callback to children components in order to update a specific child component

I am currently working on developing a Navbar component that undergoes slight changes when a user logs in through a SignIn component. Here is an overview of how my application is structured: Initially, I have defined a state in the App component where aut ...

json_encode has stopped functioning (now)

Recently, I encountered a strange issue. I've been trying to display chart data, but the JSON_ENCODE function that is supposed to convert my data into JSON format is not returning anything. It was working fine before when I had less data, but now it&a ...

What is the best way to display each value from the array arr, containing strings, on separate lines?

Can you complete the function below to display each value in the array 'arr' on separate lines? <!DOCTYPE html> <html> <head> <title> ...

Can you please explain the distinction between the statements var a = b = 2 and var a = 2; var b = 2;

Whenever I try to declare a variable within a function, I encounter an issue. var b = 44; function test(){ var a = b = 2; } However, the following code works without any problems: var b = 44; function test(){ var a; var b = 2; } The global ...

Using Angular 5 to link date input to form field (reactive approach)

I'm encountering an issue with the input type date. I am trying to bind data from a component. Below is my field: <div class="col-md-6"> <label for="dateOfReport">Data zgłoszenia błędu:</label> <input type="date" formC ...

What is the best way to extract the JSON data from a client-side GET request response?

Here is my request from the client side to the server in order to retrieve JSON data. fetch("/" + "?foo=bar", { method: "GET", }).then(response => { console.log(" ...