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

Modifying text input in Angular

I am working on an Angular form that includes a text input which I would like to be able to edit by clicking on the edit button. Within the form, there are 3 buttons available: edit, cancel (which discards changes), and save (which saves changes). When t ...

Using Material-UI to implement a Link component from the react-router library

I'm having trouble integrating the <Link/> component into my material-ui AppBar. Here is my navigation class: class Navigation extends Component { constructor(props) { super(props) } render() { var styles = { appBar: { ...

What is the most effective way to display a card with varying values depending on the user's input in a form?

For a while now, I've been grappling with a particular challenge. In my project, I am utilizing multiple states to display values within a card after they are entered into a form. The first state captures the values and modifies the initial state, whi ...

Reset the jQuery star-rating plugin

I came across a useful plugin for star ratings called JQuery Star Rating by Daniel Upshaw. My question is, how can I reset the stars in a form using this plugin? $("#btn-reset").on('click', function() { //resetting other inputs $('#st ...

A difference in the way content is displayed on Firefox compared to Chrome, Edge, and Safari

Recently, I encountered an issue with a tool I had developed for generating printable images for Cross-Stitch work. The tool was originally designed to work on Firefox but is now only functioning properly on that browser. The problem at hand is whether th ...

Finding the Middle Point of a Circle Using CEP/JavaScript

Using a specific set of calculations, I am able to create a circle in this manner: var yMinCir = height - 1515.80/2.667+8.5; var yMaxCir = height - 1545.80/2.667+8.5; var myCircle = page.ovals.add({geometricBounds:[yMinCir, 1312.63/2.667+8.5, yMaxCir, 1342 ...

Enhance the "content switcher" code

I have been working on improving my "contenthandler" function. It currently changes different articles when I click different buttons, which I am satisfied with. However, I believe there may be a better approach to this and would appreciate any advice on h ...

Utilizing ng-repeat $index for locating an element within an array

Within my $scope, there is a property called $scope.cars, which is an array of cars. Users have the ability to delete a car from this array. When calling the delete function deleteThis, I pass the $index parameter created by ng-repeat. However, in the Ja ...

pre-iframe loading function

Is it possible to capture the state of an iframe while data is loading? The onload event only fires once all content has finished loading. I would appreciate any assistance with this issue. Thank you. ...

Which is better for toggling between images/icons: a switch statement or a ternary operator?

I have a unique challenge where I am dealing with a dynamic list of thumbnails. Some of the items in this list are images, while others need to be represented by icons. My goal is to display either an image or an icon based on the contentType of each item. ...

Instead of relying on traditional AJAX for receiving remote commands, consider using a new Image object in your code like this: `var

How efficient is the following method: var i = new Image(); i.src = 'http://secondary.domain.com/command.gif?command=somecmd&rand=' + ...epoch time....; ... utilizing mod_rewrite to redirect the above URL to a PHP script ... Is this an effe ...

Is it possible for me to input a variable into the logical process of if(isset($_FILES['whatever']))?

I have recently started learning PHP and I'm in the process of creating a dynamic page that will update based on which form buttons are clicked. The functionality is working correctly, but my goal is to enable users to upload multiple files - either P ...

Ajax received a response from http 409 and is now parsing it

Hey there! I've been working on parsing out the message object using Ajax, and I'm having a bit of trouble getting a reference to messages.msg. It's strange because it displays perfectly fine in Postman, but for some reason, I can't see ...

Automatically executing JavaScript function on an AngularJS webpage

Within my AngularJS webpage, I have implemented a self-invoking function. One crucial aspect of this function is the getData() method, responsible for making Ajax calls to fetch data upon page load and user interactions. <script type="text/javascript"& ...

Choose a sibling element using CSS styling

As I'm developing an AngularJS component, I am on the quest to identify ANY sibling of a particular tag, irrespective of whether they are div, span, or p. I'm hoping for a CSS-native solution that resembles something along the lines of div:siblin ...

The MUI Autocomplete filterOptions is not effectively filtering out all options as expected

Hey there! I'm facing an unusual situation with my Autocomplete feature, which has been heavily customized to meet certain restrictions and requirements. The issue I am encountering is related to filtering. Despite successfully filtering the results ...

What is the best way to pass a variable and its corresponding state-updating function as a prop in a React component?

Considering I have a variable defined as follows: const [APIKey, setAPIKey] = useState([]) Is it possible to group these together into a single variable and then pass it as a prop? const passAPI = {APIKey, setAPIKey} Here is my approach to passing it alo ...

Guide on securely presenting an HTTP-only cookie as a bearer token, without the use of Angular.JS

Can a JWT be securely stored as an HTTP-only cookie and also used as a bearer token without relying on Angular.JS? I believe this could be achievable, as Angular.JS offers similar features (although I'm not sure if they use an HTTP-only cookie to sto ...

Activation of navigation buttons in the Vue Full Calendar control the movement to the next and previous

In my current project, I am utilizing https://www.npmjs.com/package/vue-full-calendar. However, I have encountered an issue when trying to receive callbacks or triggers from the next and previous buttons on the calendar. My backend API is structured aroun ...

Using jSLint in combination with Angular leads to an unexpected error regarding the variable "$scope"

When performing a jSLint check on my Angular-based app, I encountered an "Unexpected '$scope'" error. To replicate the issue, you can try inputting the code snippet below into jslint.com. I'm puzzled as to why the first function declaration ...