Stopping halfway through a jQuery toggle width animation to close again

Perhaps the question may be a bit unclear, but allow me to provide an example. When repeatedly clicking the button that toggles the width, the div continues to animate long after the button press, which is not visually appealing. My desired outcome is for the div to pause midway through the animation and then reverse direction when the button is pressed again, rather than completing its current animation.

$(document).ready(function() {
  $('.menuToggle').click(function() {
    $(".menuContainer").animate({
      width: 'toggle'
    });
  });
});
.menuContainer {
  height: 100px;
  width: 50px;
  float: left;
  position: relative;
  background-color: black;
  display: none;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="menuContainer">
  <!-- Menu Items -->
</div>
<h4 class="menuToggle">Show Menu</h4>

Check out this fiddle link to see exactly what I mean. Feel free to spam the "Show Menu" button.

https://jsfiddle.net/x14usdga/5/

I would greatly appreciate any assistance, as I have searched extensively but cannot find a solution to my issue.

Answer №1

If you need to stop an animation, you can use the .stop() method. Here's an example:

$(document).ready(function() {
  $('.menuToggle').click(function() {
    $(".menuContainer").stop().animate({
      width: 'toggle'
    });
  });
});
.menuContainer {
  height: 100px;
  width: 50px;
  float: left;
  position: relative;
  background-color: black;
  display: none;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="menuContainer">
  <!-- Menu Items -->
</div>
<h4 class="menuToggle">Show Menu</h4>

Answer №2

Make sure the element is not currently in an animation before starting a new one

https://api.jquery.com/is/
https://api.jquery.com/animated-selector/

$(document).ready(function(){
  $('.menuToggle').click(function(){
    if( $('.menuContainer').is(':animated') ) { return false; }
    $(".menuContainer").animate({width: 'toggle'});
  }); 
});
.menuContainer{
    height: 100vh;
    width: 15vw;
    float: left;
    position: relative;
    background-color: black;
    display: none;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="menuContainer">    
    <!-- Menu Items -->
    </div>
    <h4 class="menuToggle">Show Menu</h4>

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

Track and monitor data modifications in Vue.js

I recently incorporated a Bootstrap Vue Table into my application and wanted to monitor user activity as they navigate through the pages using the pagination feature. Here is where you can find more information on the Bootstrap Vue Table To achieve this, ...

There seems to be a glitch in my PHP comment validation function—it does not seem to be functioning

This form is contained in a PHP file named single.php. <form action="comments.php" method="post" > <?php include(ROOT_PATH . "/app/helpers/formErrors.php"); ?> <input type= "hidden" name="id" value= & ...

Implementing AngularJS to store data in a JSON object

Imagine having an animals.json file with the following details: { "animals": { "elephant": { "size": "large" }, "mouse": { "size": "small" } } } Now, let's say this data is being added to the controller scope: anim ...

Preventing Users from Uploading Anything Other than PDFs with Vue

I am currently working with Bootstrap-Vue and Vue2. Utilizing the Form File Input, I want to enable users to upload files, but specifically in PDF format. To achieve this, I have included accept="application/pdf": <b-form-file v-model=&quo ...

Updating a Rails form with a dynamically changing belongs_to select field

My Rails3 app has a Site model, connected to a Region model which belongs to a Country. Currently, the site form includes a select field for Region filled from the Region model. However, I want users to update this list dynamically. I attempted to create ...

problem with transmitting information through $.ajax

I'm facing a frustrating issue with the $.ajax()... function in my PHP code. I am unable to retrieve the data sent by the ajax request. <?php if ($_POST){ include 'Bdd_connexion.php'; $filiere = $_POST['filiere']; ...

Utilizing external Cascading Style Sheets in AngularJS 1

Can an external CSS be applied to a component in AngularJS1? If yes, then how can it be done? I have only seen examples of applying inline css... ...

Display a modal dialog showcasing the progress while making an ajax request

I am working with an Excel sheet that contains over 30,000 records. My goal is to insert each record into a database and display a modal window with a progress bar showing the percentage of completion along with details such as total number of records, num ...

When accessing the website through an AJAX call and utilizing the Html.AntiForgeryToken() function, make sure the essential anti-forgery form field "__RequestVerificationToken" is included

My Controller has two action methods, both annotated with [ValidateAntiForgeryToken()]. The corresponding view includes @Html.AntiForgeryToken(). One of the methods (GetVendorOrders), which binds results to a Kendo grid, executes successfully. However, the ...

Setting the selected value of a static select menu in Angular 2 form

I'm having an issue with my Angular 2 form that includes a static select menu. <select formControlName="type" name="type"> <option value="reference">Referentie</option> <option value="name">Aanhef</option> &l ...

Determining whether the user has a token stored in the localStorage is a crucial step in my

I have an app that calls a Login API and returns a token. I store the token in localStorage, but I'm unsure how to validate if the user has a token to log in. What steps can I take to solve this? Below is my login page where I store the token in loca ...

Selecting a date in a pop-up

In my PHP application, I have incorporated a date selection feature within a modal dialog. However, when clicking the control, the calendar appears in the left corner of the page and remains visible even after selecting a date. Additionally, clicking elsew ...

Angular - Automatically update array list once a new object is added

Currently, I'm exploring ways to automatically update the ngFor list when a new object is added to the array. Here's what I have so far: component.html export class HomePage implements OnInit { collections: Collection[]; public show = t ...

Performing an HTTP request response in JavaScript

I am trying to make an HTTP request that returns the data in JSON format using 'JSON.stringify(data)'. var xhr = new XMLHttpRequest(); xhr.open("GET", "/api/hello", true); xhr.send(); xhr.onreadystatechange = function () { console.log(xhr.r ...

Learn the process of dynamically wrapping component content with HTML tags in Vue.js

Hey there! I'm looking to enclose the content of a component with a specific HTML tag, let's say button for this scenario. I have a function that dynamically returns a value which I use as a prop. Based on that, I want to wrap the component&apos ...

What is the function of this.handleClick that is positioned on the LEFT side of the = operator?

I'm struggling to understand the usage of this in an ES6 constructor. Initially, I grasped the following concepts (see example below): - We utilize this.height = height; to introduce a new instance variable. - Adding a new instance method with cl ...

The background color of the div or section is stubbornly refusing to change, no matter how much I tweak it

.forBackground { background-color: white; } .kontaktUndMapContainer { width: 100%; padding: 20px; color: gray; text-align: center; } .überschriftKontakt { margin-bottom: 20px; } .überschriftKontakt2 { margin-top: 20px; margin-bottom: 2 ...

Enhance your Highmap R or JavaScript visualization with a unique custom legend feature

Provided below is my code snippet, output$map <- renderHighchart({ region_map = hcmap("countries/nz/nz-all") highchart(type = "map") %>% hc_title(text = "Average") %>% hc_add_series_map(map = region_map, df = data1, joinBy = " ...

Text that sparkles: one part in italics, one part not?

Within my shiny app, I have a textOutput component called "acronym" where I intend to display some text with half non-italicized and half italicized. My attempted approach was as follows: output$acronym_1 <- renderText(paste("SID SIDE:", tags$em("Side ...

A dynamic AJAX menu showcasing content in a dropdown format, away from the conventional table layout

My dropdown select menu is correctly populating with data, but the output always appears outside of the table. Can anyone spot the issue in my code? Any suggestions or ideas are greatly appreciated! Thanks in advance, select.php <?php $q = $_GET[&apos ...