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

What is the best way to convert exponential values to decimals when parsing JSON data?

var value = '{"total":2.47E-7}' var result = JSON.parse(value); Looking to convert an exponential value into decimal using JavaScript - any suggestions? ...

The issue of the keyboard disappearing on Chrome for Android while switching between different input

Issue with Input Switching on Chrome for Android I am facing difficulty when trying to switch between two input fields. The HTML code is as follows: <input type="text"/> <input type="text"/> When I enter text in the first input and click on ...

The height of the Material UI dropdown is displaying in an improper manner

I'm currently experimenting with the Material UI dropdown on my website, utilizing the react-select library. However, I've encountered an issue where the UI gets compromised when using an option that exceeds the width of the dropdown. If anybody ...

Combine theme configuration options within Material-UI

I am interested in setting up custom theme rules in Material-UI. My goal is to create both light and dark themes and extend them with some shared settings. My initial idea was to store the common settings for the light and dark themes in a separate variab ...

Sending Information within Controllers with AngularJS

I have a unique scenario in my application where I need to pass input from one view to another. I have set up a service as shown below: .service('greeting', function Greeting() { var greeting = this; greeting.message = 'Default&ap ...

The Eclipse Phonegap framework is experiencing difficulty in loading an external string file with the jquery .load function

A basic index.html file has been created to showcase a text string from the test.txt file by utilizing the .load function from the jQuery library. The goal is to insert the textual content into an HTML (div class="konten"). The provided HTML script looks ...

Trigger an action in the clean-up function of useEffect

I am facing an issue with a form component in a Material UI <Tab /> where users can update their address information. The data is fetched from the API using redux-thunk, and the form fields are pre-filled with server data before the update occurs. T ...

The case of the elusive Firefox overflow: hidden glitch

Recently, I integrated an image slider into my web design and it displayed perfectly on Internet Explorer and Chrome. However, when viewed on Firefox, I encountered a strange problem where the images in the slider were being pushed towards the right side o ...

Are `<text>` nodes unable to utilize ligature fonts in CSS/SVG?

Check out this JsFiddle demo: http://jsfiddle.net/d0t3yggb/ <link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet"> <div class="material-icons">add add add add</div> <svg width="100%" height="100% ...

Discover the art of implementing linear gradient backgrounds in Tailwind css effortlessly

Is there a way to incorporate this specific color scheme into my background? linear-gradient(355.45deg, #FFFFFF 11.26%, rgba(255, 255, 255, 0) 95.74%) I have knowledge on how to implement this color using regular CSS, but I'm curious about how it can ...

Guide on creating an autonomous select-all checkbox to show table columns

How can I create checkboxes with a "Select all" option and the following functionality: Check one or more checkboxes to show specific table columns. Uncheck them to hide the columns (toggle). Select the "Select all" checkbox to display all table columns. ...

Disable the full screen camera mode on iOS browsers while live streaming camera video

I recently completed a tutorial on capturing video streams from the front or rear camera of an iPhone using JavaScript. The tutorial can be found at this link. While testing the functionality on my desktop browser, everything worked perfectly. However, wh ...

Is it possible to apply a CSS Transition to just one specific type of transform?

Can you animate just one type of css transform using transitions? My css looks like this: cell{ transform: scale(2) translate(100px, 200px); transition: All 0.25s; } Now I only want to animate the scale property. I could use position:absolute with ...

Issues with applying different styles in a React Component based on prop values are hindering the desired outcome

I am currently working on a Display component that is supposed to show an item. The item should be styled with the css property text-decoration-line, applying line-through when the Available prop is set to false, and no decoration when set to true. Howev ...

What is the method for transferring AJAX response data to PHP variables?

Is there a way to pass the result value from my code to a PHP variable? Here's what I have so far... billingCoffee.php $("#linkAddSize").click(function(e){ e.preventDefault(); var txtCoffeeName = document.getElementById("txtC ...

Comparing currency to double in handlebars: a comprehensive guide

I've been working with Handlebars.js and encountered an issue when trying to compare product prices above $35. The problem arises from the fact that prices are stored as "$54.99" which gets treated as 0 when compared to a number. How can I effectively ...

Can AdonisJS 4.1.0 support conditional queries?

I am exploring the capabilities of AdonisJs query builder by referring to their documentation at Currently, I am attempting to replicate a scenario similar to the one demonstrated under the 'Conditional Queries' section: const query = Database. ...

Guide to incorporating vertical scrolling for a grid of items in Material UI

Is there a way to implement vertical scrolling in a grid container so that when the height of components exceeds a certain maximum, they can be scrolled through vertically? ...

The console is displaying the array, but it is not being rendered in HTML format in AngularJS

Can you please review my App.js file and let me know if there are any mistakes? I have provided the necessary files index.html and founditemtemplate.html below. Although it is returning an array of objects in the console, it is not displaying them as inten ...

What is the best way to start tiny-slider automatically once the video has ended?

I am currently using the tns-slider plugin and have a setup with 3 slides (2 photos and 1 video). <div class='tiny-slider'> <div class='slide slide1'> <div class='video-slide'> <video id=&qu ...