I am struggling to run the jQuery animation that adjusts the width more than once

My goal is to allow the user to expand and retract a <div> element upon clicking. The desired behavior is for the <div> to expand when clicked, and then retract back to its original width when clicked again.

However, when testing this functionality, I encountered an issue where the <div> would expand on the first click but fail to retract on the second click. Despite confirming that the click event is being triggered with console.log(), the animation does not run again. Even when adding a function at the end of the animation to log a message, the <div> remains unchanged. Various attempts have been made to solve this problem without success.

Shown below is one of the attempted solutions. Alternative methods such as using removeClass().addClass() or implementing two separate click events have also been tested, all resulting in the same issue.

$(document).ready(function() {
  var count = 1;
  var modulo = 1;

 $("#animateMe").click(function() {
   modulo = count % 2;
   count += 1;
   $("#animateMe").animate({
     width: (modulo = 0 ? 500 : 250)
   });
 });
});

HTML:

<div id="animateMe"></div>

CSS:

#animateMe  {
  background-color:blue;
  height: 100px;
}

Check out the codepen example for reference: https://codepen.io/ethan-vernon/pen/mLqBxR

Answer №1

Ensure your condition is modulo == 0 instead of modulo = 0. The latter will always set the value of modulo to 0, resulting in false and setting the width to 250 on each click.

$(document).ready(function() {
  var count = 1;
  var modulo = 1;
   
  $("#animateMe").click(function() {
    modulo = count % 2;
    count += 1;
    $("#animateMe").animate(
      {
        width: (modulo == 0 ? 500 : 250)
      }
      
    );
  });
  
  
});
/*
#animateMe {
  background-color: #AAAAAA;
  width: 100px;
  margin: 15px;
  height: 60px;
}
*/

#animateMe  {
  background-color:blue;
  height: 100px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="animateMe">
 
</div>

Answer №2

It has been pointed out by other users that you are attempting an assignment rather than a comparison. To improve readability and adhere to best practices, it is recommended to use triple equality (===) instead of convoluted syntax.

if (modulo === 0) {
   width = 500
}
else {
   width = 250
}

Instead of checking the modulo variable, you can simplify your logic with a straightforward assignment:

$("#animateMe").animate({
   width : 500 - (modulo * 250)
});

Alternatively, you could do:

$("#animateMe").animate({
   width : [500, 250][modulo]
});

(considering that modulo is either 0 or 1)


Trying to use removeClass().addClass() and separate click events resulted in the same issue.

A single click event listener, toggling just one class, can suffice. You can achieve this with plain JavaScript and CSS transitions like so:

CSS

#animateMe  {
  background-color:blue;
  height: 100px;
  width: 500px;
  transition: width 1s 0s;
}

#animateMe.half {
  width: 250px;
}

JavaScript

var el = document.getElementById('animateMe');
el.addEventListener('click', function() {
   this.classList.toggle('half') 
});

Check out the Codepen Demo 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 eliminate the background color from one span after selecting a different one?

I created a span element that changes its background color when clicked, but I want the background color to switch to the newly clicked span while removing it from the previously clicked one. Can someone help me achieve this? CSS list-sty ...

Animations in Angular fail to operate within mat-tabs after switching back when custom components are being utilized

I am facing a similar issue as Olafvv with my angular 16 project. The problem occurs in a mat-tab-group where the :enter animations do not work when navigating away from a tab and then returning to it. However, in my case, the issue lies within a custom su ...

Create a rectangle on a canvas using coordinates that have been translated relative to the original image

Displayed on the screen is an image element that undergoes a css transform: rotate(degree), with degree ranging from 0 to 360. This transformation makes the image appear rotated, even though its original orientation remains unchanged. Given this scenario, ...

What is the best way to align these Iframes in the center?

This is the html <div class="main_content"> <section class="episodio"> <article class="contenedor_episodios"> <h2>Episodios</h2> <div class="episodio_spotify" ...

Ways to evenly distribute form fields with Bootstrap 4

I've been attempting to achieve a more balanced distribution of these fields, but so far I have not succeeded: Current https://i.sstatic.net/6R1wb.png Expectation https://i.sstatic.net/azior.png This code segment needs attention: <div class=&quo ...

"Utilizing jQuery to select elements for the purpose of preventing default

$('input[name=boxes], .item_add a ').on('click', function(e) { e.preventDefault(); //perform common actions } Is it possible to stop the default scrolling behavior when clicking on a link [.item add a], while still allowing the defa ...

What exactly is the significance of "utilizing a universal class name"?

In my current project, I am utilizing Material-UI version 3.1.2 to create the interface. Previously, when I was using Bootstrap4, I included style="overflow-y: scroll; height: 100%" in my head tag to ensure a scrollbar is always present, preventing the ap ...

Deactivate the focus state when hovering over different items in the navigation bar

Currently facing an issue with my Navbar items having underline animation on hover. Once clicked, the animation persists. However, when hovering over a neighboring navbar item, the underlines appear next to each other, creating the illusion of one long lin ...

How to reset the value in a select box using jQuery

Looking at my code, I have some markup and jQuery javascript set up like this: let color_select = $('select#SelectByColor'); color_select.val([]); <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></sc ...

How can the "Search within page" feature locate words that are divided between different elements?

I need to present text in groups of a specific length while still being able to search for text that spans multiple groups on the page. Additionally, I want to include a character above each group. My current approach is as follows: body { marg ...

Javascript failing to choose background color from an array

I am attempting to create a subheader with varying colors, similar to the one found on the Ask Different page. However, instead of manually assigning colors, I am looking to have it randomly select a color from a Javascript array. I have already outlined ...

Premature adjustment of images to window size changes

How can I make the images inside a divider move down when the right-end of the browser reaches them? Currently, they start moving down before the edge of the window is reached. Any suggestions on how to fix this? JSFIDDLE: https://jsfiddle.net/prtdaay1/2/ ...

Stylized widget for showcasing a list of cities for meetups

After extensive searching, I have yet to find a solution to stylize the "City List" widget for Meetup. The specific widget I am focusing on is the first one listed here. () Despite exploring various options such as the widget foundry and conducting onlin ...

Ensure that the div element spans the entire width of the screen

Having issues working with the div tag and encountering this problem: The left side doesn't extend as far as the right side, despite testing in multiple browsers. Here is the HTML code being used: <!DOCTYPE html> <html lang="en"> <h ...

"Enhancing User Interactions with Hover Effects and Click Events

I am working on a project that involves 4 links that alter the position of 4 divs within a webpage. In order to change the color of the links when hovering over them, I have implemented the following jQuery script: $('a.menua').hover(functio ...

In Javascript, the DOM contains multiple <li> elements, each of which is associated with a form. These forms need to be submitted using AJAX for efficient

I have a list element (ul) that includes multiple list items (li), and each list item contains a form with an input type of file. How can I submit each form on the change event of the file selection? Below is the HTML code snippet: <ul> ...

Calculating dimensions for parents and their children

Could someone please explain to me why the size of #child is different from that of #parent? <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.or ...

Form submission fails to trigger AJAX execution

When a form is submitted, I have the jQuery ajax code below that should be executed: <script src="http://code.jquery.com/jquery-1.10.1.min.js"></script> <script> $("form").submit(function() { $.ajax("/myapp/rest/customer/created ...

Center and left-align elements

I want to make my list items align like the dropdown menu shown at the bottom of the picture. The items in the dropdown are centered and aligned vertically in a single line. How can I achieve this effect? Below is the code snippet I am using: <div c ...

Solution to ensure fixed header with correct z-index placement

Everything is functioning correctly, except for the issue that arises when scrolling down to view thumbnails. The left bar covers the thumbnail section, making it impossible to select items. I suspect that the z-index of a div is causing this problem. I ha ...