Displaying and hiding content with a single button

I'm working on a slide-in content feature that appears from the left when clicking on the bars icon. Initially, I set it up with separate buttons for opening and closing the content by moving the page left and right. Now, I'm attempting to achieve the same functionality using just one button – open on first click and close on second. As a newcomer to Javascript/jQuery, I've been researching online and making adjustments to the code as I go along to try to get it right.

For a demonstration of the issue, you can view my JsFiddle.

Javascript:

var main = function() {
$('.icon-menu').click(function(){
  $('.menu').toggle(
    function(){
      $('.menu').animate({
        left: "0px"}, 200);
  },
    function(){
      $('.menu').animate({
        left: "600px"}, 200);
  });
});
}; 

$(document).ready(main);

HTML:

<div class="container-fluid">
    <div class="row">
        <div class="icon-menu icon-close col-xs-1">
            <i class="fa fa-bars fa-4x"></i>
        </div>
    </div>

     <div class="row">
         <div class="menu col-md-5">
            <div class="about-text col-md-offset-1">
                <h1>About</h1>
                <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Similique, quia.</p>
            </div>
        </div>
    </div>
</div>

CSS:

body {
background-color: grey;
}

.menu {
background-color: blue;
left: -600px; /* equal to width */
height: 100%;
position: fixed;
/* width: 600px; */
}

.about-text {
color: #fff;
font-size: 15px;
text-decoration: none;
}

.icon-menu {
color: #fff;
cursor: pointer;
padding-bottom: 25px;
padding-left: 25px;
padding-top: 25px;
text-decoration: none;
z-index: 0;
background-color: red; /* marking button location */
}

.icon-menu i {
margin-right: 5px;
}

NOTE: I am aware that toggle has been deprecated in newer jQuery versions, but it was the best fit solution for my specific challenge.

Answer №1

When using jQuery version 1.8, the toggle function behaves like a click function on its own, eliminating the need for a separate click function.

Check out this Demo

http://jsfiddle.net/ue36sfcs/

Here's the code snippet:

 $('.icon-menu').toggle(
    function(){
      $('.menu').animate({
        left: "600px"}, 200);
  },
    function(){
      $('.menu').animate({
        left: "0px"}, 200);
  });

For versions of jQuery above 1.8, you can set an 'on' and 'off' flag as shown below.

See the Demo here:

http://jsfiddle.net/eae779xo/

Code Snippet:

var on = "no"
$(document).on("click", ".icon-menu", function(){      
    if (on == "no") { 
        $('.menu').animate({ left: "600px"}, 200);
        on = "yes";
    } else { 
        $('.menu').animate({ left: "0px"}, 200);
        on = "no";
    }
})

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

Personalized Grid Featuring Imagery

As I delve into web development, I have been using libraries like Bootstrap3 to enhance my skills. However, I want to expand my knowledge further by understanding and being able to replicate some of the functionalities available in Bootstrap on my own. Cur ...

Expanding Logo on Mobile with Javascript

I'm encountering some difficulties with the site. When viewing it on a mobile device or resizing the browser to phone size, if you scroll down and then back up, the logo appears oversized. I want it to remain small like it was at the beginning (refres ...

Guide on incorporating factories with Ionic/Angular JS while utilizing phonegap

I've been experimenting with global variables in my ionic/angular + phonegap app project by implementing a factory service. However, even adding a simple factory service like the one below somehow disrupts the app and causes all screens to turn compl ...

Having trouble aligning Bootstrap SVG icons to the center

I'm struggling with getting the svg icons centered on my welcome.blade.php file. Instead, they appear shifted to the right. I would really appreciate any help or advice on how to fix this issue. Check out a screenshot here My welcome.blade.php code s ...

Storing state or data in React for persistence when users navigate between pages or use the browser's back

In the process of developing a small SNS app with React (Gatsby.js), I encountered a challenge. My goal is to maintain state in previous pages even when navigating back using the browser, similar to popular platforms like Twitter and Instagram. However, I ...

JavaScript - Combine objects by summing values with matching keys

Below is the given array : [ { "Date": "2019.07.08", "Organisation": "A", "Client": "Client1", "Product": "Pen", "Quantity": "1120" }, { "Date": "2019.07.08", "Organisation": "A", "Client": "Client1", "Product": " ...

Is it possible for someone to enhance the code by minimizing the if-else statements through the implementation of

Is there a way to optimize this piece of code? Looking for suggestions on reducing the if-else conditions using a for loop. I'm working on submitting form data through ajax in Laravel. When validation fails, I want to display errors next to the resp ...

What is the method for sending an AJAX request with a dynamically looping ID number parameter in the URL

I am looking to make multiple AJAX calls with a loop parameter named [id] in the URL, starting from request.php?id=1 and ending at id=9. I want to send each call after a 3-second delay. As a JavaScript beginner, I'm unsure of where to begin implementi ...

I am struggling to save a second variable that I received into my function

There is a function in my code that takes two values as input, both formatted like this: MyFunction("word1","word2") However, when the function receives the values, it looks like this: MyFunction(test1,test2){} The issue I'm facing is with storing ...

Issues with functionality of Tumblr share button

I've been attempting to integrate a Tumblr share button on my online store, but I'm having trouble getting the Tumblr Share Button (see here) to function properly. My goal is to allow users to share a customized picture of a product and include ...

Tips for preserving images while browsing a website built with Angular single-page application

Utilizing Angular's router for component navigation has been beneficial, but I am facing an issue with component reloads when going back. To address the problem of content reloading from the server, I have implemented a solution where the content arra ...

What is the process for altering the background color of a modal?

I'm trying to figure out how to change the background color of my modal once it's displayed, similar to this example: https://i.stack.imgur.com/fOUDZ.png. I want the background color to cover the entire page and not just the modal itself. When I ...

Leveraging event listeners in conjunction with React's useEffect function

Check out the code example on Code Sandbox here Hey there, I'm trying to implement a feature where clicking a button inside a container displays a box. I've set up an event listener so that when you move your mouse outside the container, the box ...

"Maximizing the power of AJAX in Github using Laravel for

Currently working on a web application using Laravel with a structure similar to Spotify. My objective is to create a seamless experience for the users by ensuring that when they click on a link or element, the page content changes dynamically without havi ...

Is there a way to defer a for loop in Angular?

In my Angular project, I am working on a sorting visualizer using the chart.js bar chart. Currently, I am focusing on visualizing bubble sort and I want to incorporate a delay in each iteration of the inner loop. I assume you are familiar with the loop s ...

Is there a way for me to retrieve dynamic text?

I used an "IF" statement to display dynamic text - if it's null, show something, otherwise show something else. However, I am getting a blank result. What did I do wrong? <View style={styles.rightContainer}> { () =>{ if(t ...

"An issue with preventing default behavior when clicking on a jQuery element

I need some assistance preventing a JQuery onclick function from scrolling the page to the top. I have tried using preventDefault() without success. You can find the code on this website: Below is the code snippet that I am currently using: $( document ...

What is the most effective method for linking css and js files?

Assuming your website's domain is domain.com, and you have the following directories and files: - index.php <panel> - panel.php <css> - style.css <js> - jQuery.js In index.php, you can reference a css file like "css/style.css" or " ...

Resetting CSS animations in Vue is a simple process that can be achieved

Here is a sample list: var v = new Vue({ 'el' : '#app', 'data' : { 'list' : [1,2,3,4,5,6,7,8,9,10] }, methods: { activateClass($event){ $event.target.classList.remove('animate'); ...

Sliding Dropdown Menu with Dynamic Title Change Upon Selection

I'm having an issue with a dropdown menu on hover that slides down and then back up. The active list item serves as the title of the dropdown. When a user clicks on an <li>, it becomes active and receives the class active-markup-style which sets ...