Tips for creating animations with multiple elements that share the same classes

I am trying to create expandable boxes that can open onclick and close again by clicking on the X. The issue I'm facing is that the close jQuery function isn't working. However, my main concern is how to optimize the code so it doesn't become overly long with repetitive lines for each box/element.

When a box/element is clicked, it should expand along with its content in the order they appear. Subsequently, it should be possible to close them individually and click on another element with the same effect using similar code. How can I make sure that the site knows which element has been clicked?

Thank you in advance :)

Answer №1

If you have multiple boxes that need to expand or shrink when clicked, a solution is to assign them all the same class - boxExpandable, for example, with an initial width. When a user clicks on a boxExpandable, you can toggle the .expanded class which increases the width.
To show specific content only when a box is expanded, enclose it in a .showWhenExpanded class as demonstrated below.

$(document).ready(function(){
  $('.expandableBox').on('click', function(){
    $(this).toggleClass('expanded');
  });
});
.box {
  margin-bottom: 10px;
  padding: 15px;
  width: 40%;
  border: solid 5px goldenrod;
  transition: background-color .4s, width .4s;
}

.box:hover {
  background-color: #32cd32;
}

.box.expanded {
  width: 80%;
}

.showWhenExpanded {
  display: none;
}

.box.expanded .showWhenExpanded {
  display: inline-block;    
}
<script src="//code.jquery.com/jquery.js"></script> 

<div class="content">
  <div class="box expandableBox">
    <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. <span class="showWhenExpanded">Duis aliquam nunc sit amet ante lacinia, vitae dictum erat egestas. Duis rutrum vitae orci vitae euismod.</span></p>
  </div>
  <div class="box expandableBox">
    <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. <span class="showWhenExpanded">Duis aliquam nunc sit amet ante lacinia, vitae dictum erat egestas. Duis rutrum vitae orci vitae euismod.</span></p>
  </div>
  <div class="box expandableBox">
    <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. <span class="showWhenExpanded">Duis aliquam nunc sit amet ante lacinia, vitae dictum erat egestas. Duis rutrum vitae orci vitae euismod.</span></p>
  </div> 
</div>

For reference, check out this codepen 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 arrange an array to display country data based on Covid cases in descending order rather than alphabetical order?

This particular code snippet retrieves Covid19 statistics data using an API. Currently, it displays the data for covid cases of all countries in Alphabetical order. However, I am looking to present the data in descending order, meaning that the country wit ...

Implementing setDoc with Firebase-Admin using Typescript in Firestore

I'm having issues with my code in config/firebase.ts: import { initializeApp, cert } from 'firebase-admin/app'; import { getFirestore } from 'firebase-admin/firestore' const firebaseAdminApp = initializeApp({ credential: cert( ...

Implementing a New Port Number on a ReactJs Local Server Every Time

As a newcomer to ReactJS, I recently encountered an issue while working on a project that puzzled me. Every time I shut down my local server and try to relaunch the app in the browser using npm start, it fails to restart on the same port. Instead, I have ...

Tracking the User Interface efficiency of a Java Applet running on a website

I have developed a Java Swing based messenger applet that runs smoothly on browsers. My next step is to host this applet on a webpage and allow users to test it out. I want to track the time they spend on each task while using the messenger, as well as any ...

steps to initiate re-render of rating module

My first experience with React has been interesting. I decided to challenge myself by creating a 5-star rating component. All logs are showing up properly, but there seems to be an issue with the component not re-rendering when the state changes. Thank you ...

Issues arising from the combination of two variable values

I'm facing some issues trying to combine two variables and insert them into an ajax post URL. Unfortunately, I keep receiving error messages. Let me share what I have attempted so far: var photoId = 227; var jobId = 334; $.ajax({ type: "POST" ...

filtering out specific sections of HTML using xPath

I am currently attempting to scrape information from this page My approach involves using xPath to select specific elements. Here is a snippet of my code: $safeFlag = true ; //*[@id="tabset_productPage"]/dd[1]/div/div //HAVE TRIED THIS TOO //*[@id="tab ...

How can you incorporate a click function into a toggle function?

Currently, I have an accordion-style navigation set up with collapsible tabs and toggle buttons. I am attempting to make my 'tab' DIVs clickable. I implemented the following function into my code to reduce repetitive toggle() functions, but unfo ...

JavaScript Indexed Array Names: Managing Arrays with Indices

I have a collection of arrays named "list0" through "list7" which have been explicitly defined. My goal is to include each of these arrays as elements in an existing array, creating a 2D array of these defined arrays. How can I reference each 'list&a ...

Preventing Jqpivot from Automatically Sorting Data

Check out the jqpivot grid below to see detailed sales information for car rentals. You can view the complete code on jsfiddle. var data = [{ "id": 1, "make": "toyota", "model": "corolla", "fuelusagecity": "17", "fuelusagehwy": "12", ...

Responsive Image Resizing with Bootstrap for Smaller Screens

I'm struggling to resize a responsive image in Bootstrap using the carousel example on their official website. <div class="container"> <div class="other-div"> .... </div> <div id="carouselExampleCon ...

Can you elaborate on the users object found in the npm registry JSON response?

When looking at the json response of any npm package, such as jQuery for example, http://registry.npmjs.org/jquery, you may come across a dictionary called users. This dictionary contains usernames as keys and boolean values as the corresponding values. ...

The Angular Animation constantly resets with each new action taken

In my Angular project, I am working on a scaling animation for a list. I want the animation to only trigger when specific buttons (red and green) are pressed. Currently, the animation restarts regardless of what I click on. Can anyone help me troubleshoot ...

Utilizing jQuery for dynamic horizontal positioning of background images in CSS

Is there a way to set only the horizontal background property? I've tried using background-position-x and it works in Chrome, Safari, and IE, but not in Firefox or Opera. Additionally, I would like to dynamically set the left value of the position. ...

Enhancing IntelliJ IDEA's autocomplete functionality with JavaScript libraries

Is there a way to add my custom JavaScript library to IntelliJ IDEA 10.5 or 11 for autocomplete functionality? I want to specify that IDEA should recognize and suggest auto-completions for objects from my library. While it sometimes works automatically, ...

Wordpress AJAX request results in a value not found

** I have added more details, thank you for your assistance so far I am in the process of implementing an AJAX search functionality on my Wordpress site to filter properties based on type, location, and status. Being a novice at AJAX, I have been followi ...

Issue with plain CSS animation not functioning in NextJS with Tailwind CSS

I found this amazing animation that I'm trying to implement from this link. After moving some of the animation code to Tailwind for a React Component, I noticed that it works perfectly in Storybook but fails to animate when running in next dev. It si ...

JavaScript image sorting function fails to sort multiple ID elements that match

Currently, I am working on a project to develop an image sorter using toggle buttons. However, I have encountered an issue where my function is only effective for the first image ID and not any others. Below is the JavaScript function in question: functi ...

Quantifying the passage of time for data entry

Looking to create a quiz form where I can track how long it takes users to input/select answers. I attempted the following code but the timing seems off: $('input, select').on('focus', function(event) { el = $(this); name ...

Create a dynamic effect by adding space between two texts on the page

const Button = () => { const options = ['test1', 'test2', 'test3']; return ( <div style={{ position: 'absolute', left: '8px', width: 'auto', flexDirection: 'row' ...