Is there an improved method for toggling animations in CSS using jQuery compared to my current approach?

Looking to create a toggle effect for a dropdown box that appears and disappears when a button is clicked.

var clickState = false;

$("#show").on("click", function() {
  if (!clickState) {
    $(".animated").removeClass("off");
    refreshElement($(".animated"));
    $(".animated").addClass("on");
    clickState = true;
  } else if (clickState) {
    $(".animated").removeClass("on");
    refreshElement($(".animated"));
    $(".animated").addClass("off");
    clickState = false;
  }
});

function refreshElement(e) {
  var newElement = e.clone(true);
  e.remove();
  $(".container").append(newElement);
}
.controls {
  text-align: center;
}
button {
  display: inline-block;
}
.textbox {
  width: 280px;
  margin: 0 auto;
  background: tomato;
  padding: 10px;
}
.animated {
  max-height: 0;
  overflow: hidden;
  animation-name: none;
  animation-duration: 0.5s;
  animation-fill-mode: forwards;
}
.triangle {
  content: " ";
  width: 0;
  height: 0;
  border: 10px solid;
  border-color: transparent transparent tomato transparent;
  position: relative;
  left: 50%;
  top: -9px;
  margin-left: -7px;
}
.on {
  animation-name: slideOpen;
  animation-direction: normal;
}
.off {
  animation-name: slideOpen;
  animation-direction: reverse;
}
@keyframes slideOpen {
  0% {
    max-height: 0px;
    padding: 0px;
  }
  100% {
    max-height: 150px;
  }
}
<div class="controls">
  <button id="show">Show div</button>
</div>
<div class="container">
  <div class="animated">
    <span class="triangle"></span>
    <div class="textbox">text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text</div>
  </div>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>

Utilizing a clickState boolean variable to toggle the visibility of the dropdown box. The entire div is cloned and recreated to refresh the animation properly. The animation is controlled by applying and removing classes using the .addClass() method. While navigating through animation is new to me, I acknowledge the complexity of the code and will continue to refine it.

Answer №1

After examining your code, I have identified several potential issues that may impede scalability when applying it to multiple elements on the page:

  1. Relying on a global variable to maintain the current state.
  2. Animating all items simultaneously using the $(".animate") selector.
  3. Unnecessarily cloning and appending text, possibly leading to performance issues on larger pages.

It would be more optimal to toggle the applied classes to introduce the animation effect.

$("#show").on("click", function() {
  var $animated = $('.animated');
  var shown = $animated.hasClass('on');
  $animated.toggleClass('on', !shown).toggleClass('off', shown);
});

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

Prevent the beforeunload dialog box from appearing

Looking for a solution that is compatible with all browsers and operating systems. Referring to this resource https://developer.mozilla.org/en-US/docs/Web/Events/beforeunload This is what I have so far: window.addEventListener("beforeunload", function ( ...

What steps should I take to resolve the "Module Not Found" issue that occurs when I use the command "npm start" after setting up a new React project with npm?

Just starting out with React.js and npm and encountered an issue. After using the command: npm create react-app my-test-npm-react-app I waited for the project to be created successfully. However, when I tried running: npm start I received the followin ...

How can I break down an object with hyphenated key names?

Attempting to perform object destructuring on the following: { name: "Bryan", last-name: "Enid" } However, trying to destructure it like this is not successful: const {name, last-name} = req.body Is there an alternative method to destructure this ...

Challenges faced when dealing with MongoDB and the latest version of webpack

Struggling to navigate MongoDB and React.js, encountering issues with MongoDB dependencies. Here are the dependencies listed in package.json: "dependencies": { "dotenv": "^16.3.1", "mongodb": "^4.1.0", &qu ...

Ways to retrieve the most recent message on WhatsApp Web

I'm currently developing a JavaScript script for WhatsApp Web that will automate responses to messages in a specific group. Here is a snippet of my code: console.log('WhatsappWeb On'); function sleep(num){ setTimeout(num); } var eve ...

How can I incorporate multiple graphs into my AmCharts display?

I am new to using amcharts and have successfully implemented a code snippet to generate two graphs in a chart. The charts are loaded from an external data source specified in the code. var chart = AmCharts.makeChart("chartdiv", { "type": "serial", "d ...

I am experiencing an issue where my application, built using NodeJS, Express, and Javascript, is failing to insert form data into the database despite

I am facing a challenge with my app's MVC design pattern where I am unable to insert form information into the corresponding table in the database. Despite installing the body-parser package via npm, the form is not functioning as expected. Can anyone ...

What is the best way to allow my limit to be as greedy as possible?

I'm facing an issue with the code below where it currently only matches MN. How can I modify it to also match KDMN? var str = ' New York Stock Exchange (NYSE) under the symbol "KDMN."'; var patt = new RegExp("symbol.+([ ...

Exclude a Child with jQuery Selector

Is there a way to select the entire body excluding just one element? $("body").not('#to-exclude').mouseup(function(){ // ... }); This approach is not effective. ...

After a period of time, NodeJS abruptly crashes while processing a CSV file

Recently, I've been working on a project that involves converting CSV data into XML. To accomplish this, I have been using the fs.createReadStream() method to read the CSV file. However, I encountered an issue where the terminal crashes unexpectedly a ...

Issue with horizontal scrolling in ng-scrollbars occurs when scrolling from right to left

We are currently developing a single page application that supports two languages, one being right to left and the other left to right. For scrolling functionality, we have implemented ng-scrollbars, an Angularjs wrapper for the malihu-custom-scrollbar-pl ...

Execute the eslint loader within the node_modules of a specific directory that is npm linked and has not been compiled

One of the benefits of using webpack 4 is the ability to run eslint across the entire project folder with a specific configuration. { enforce: 'pre', test: /\.js|ts$/, exclude: /node_modules/, loader: 'eslin ...

Combine several CSS classes into a single class for easier styling

I have implemented specific styling on my webpage based on the city or state of the user. For instance, if someone is from New Jersey, the background color will be red. Currently, I am achieving this using the following method: Using a combination of HTML ...

Transfer Data from a Factory to a Controller in AngularJS

Although it may seem like a simple question, it has taken me nearly 3 hours to try and figure out what went wrong here. Perhaps someone could help identify the issue and provide a solution (it seems like an easy fix, but I'm just not seeing it). So, h ...

Create a jQuery datatable row using data from an internal array

Received a JSON response from the server: { "data": [{ "id": 1, "apiKey": "test1", "name": [{ "identifier": "1", "status": "Online" }, { "identifier": "2", "status ...

How can a loading bar be shown while a PHP page is loading?

I currently have an HTML form that directs to a PHP file upon submission. The PHP file takes some time to load due to background processes running, so I am interested in implementing a progress bar or alert to indicate when the file is fully loaded. Does ...

Is it possible to create an HTML select that displays transparent text after a selection

I'm currently working on customizing the appearance of an HTML select element with various background color options. Everything is functioning properly, but I have a specific requirement. I want the text in the dropdown options to be visible only when ...

Is it possible to restore the text to its original state?

Currently, I'm working on creating a simple website for server users to order items. However, I've encountered an issue related to the Navigator text. Here is how it currently appears: Upon inspecting the code below, you'll notice that the ...

Obtaining the anchor from the list item that shares the same ID as the cell

In the following HTML code for TD, it is appended after matching the IDs from the LI HTML code below. <td style="border-top-style: solid; border-right-style: solid; border-left-style: solid; border-bottom-style: solid" id="Communication"> Co ...

What is the best way to trigger an API call using AJAX whenever the page loads and at regular intervals using `setInterval()` function?

New to coding and seeking guidance: I have a basic AJAX feature in my project that triggers a GET API request every 3 seconds: <script> $(document).ready( function() { setInterval(function() { $.get(&apos ...