Experimenting with applying jquery .slideDown() to multiple classes in order to create dynamic animations

I am facing an issue while using .slideDown() with multiple classes. I want only one class to toggle/dropdown at a time, but currently when I press the button, all classes show up instead of just the one I want to display. How can I achieve this?
Here is my HTML:


    <!DOCTYPE HTML>
<head>
    <title>Ricoz.co.uk Rp Directory</title>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
    <script src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.10.3/jquery-ui.min.js"></script>
    <script rel="text/javascript" src="js/script.js"></script>
    <link rel="stylesheet" type="text/css" href="css/stylesheet.css">
</head>
<body>
    <div class="navbar"></div>
    <div class="char">
    <div class="picture"></div>
    <div class="text">
    Here is some text!</div>
    <button>test</button>
    </div>
    <div class="char">
    <div class="picture"></div>
    <div class="text">
    Here is some text!</div>
    <button>test</button>
    </div>
</body>


My CSS:


body{
    background-image: url(tb.jpg);
    margin: 0;
}
.navbar{
    border: 1px solid black;
    height: 50px;
}
.row{
    height: 440px;
}
.char{
    background-color: white;
    width: 200px; 
    margin: 20px;
    float: left;
}
.char > .picture{
    width: 200px;
    height: 200px;
    border: 1px solid black;
    border-radius: 200px;
}
.text{
    width: 200px;
    height: 150px;
}


JavaScript/JQuery:


$(document).ready(function(){
    $('.text').hide();
    $("button").click(function(){
        $(this).prev(".text").slideToggle();
    });
});


Thank you for your time!

Answer №1

Revamp your javascript with the following adjustments:

$(document).ready(function(){
    $('.text').hide();
    $(this).click(function(event){
        $(event.target).prev().slideToggle();
    });
});

This code snippet essentially targets the previous element (associated with the button that was clicked) and toggles its visibility. Unlike your previous approach of referencing all elements with the class .text, this method ensures that only the specific element above the clicked button is affected.

The Event object includes the target property, which represents the clicked button. By utilizing the prev() method, you can easily access the preceding element and trigger the sliding animation.

Feel free to check out the implementation on jsfiddle.

Additionally, I recommend adjusting your selector from

$(this).click(...) 

to

$('button').click(...)

as you specifically want to target buttons. For even better organization, consider adding a class like .click-button to your buttons and referencing them using

$('button.click-button').click(...) 

This approach allows you to exclude certain buttons from this particular effect if needed.

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

Place the image on the canvas

I currently have a canvas where I am able to add text layers and images from flickr. My goal is to enable users to upload an image to the canvas using the html input. For uploading images from flickr, I am using this code: $(".search form.image-search"). ...

Making sure the checkbox stays selected in an angular environment

After experimenting with Angular 9 and a custom input, I achieved the following result => https://stackblitz.com/edit/angular-ivy-rgsatp My goal was to prevent users from disabling a radio button that is currently checked. Therefore, I made changes in ...

Having trouble with Material UI ListItem and setting a custom key prop

While using Material UI for React, I encountered an issue when attempting to pass a key prop to a ListItem: A warning popped up stating that key is not a valid prop. Trying to access it results in undefined. If the same value is needed within the child ...

Ways to substitute numerous instances of a string in javascript

I have experience in developing websites using reactjs. I usually implement restAPI's with java and work with liferay CMS. In one of my projects, I created a shortcode for accordion functionality like this: ('[accordion][acc-header]Heading 1[/ac ...

A widget for Windows 7 that can handle both HTTP GET and POST requests

I'm currently working on a small gadget for our intranet and have set up a PHP file on our server for initial testing purposes. Everything seems to be functioning properly when I use the GET request method, but I would prefer to utilize POST in order ...

Parent div's overflow due to its flexbox properties

I am currently facing a dilemma with my nested flexbox setup. The primary objective is to create two responsive columns: .ColWrap, { width: 100%; box-sizing: border-box; background-color: #fff; padding: 50px 10px 50px 25px; display: fl ...

Having trouble transforming the JSON object into a usable format

Although I'm still getting the hang of JSON, please bear with me if this seems like a rookie mistake. My approach involves sending a query to a local file that performs a cURL operation on an external site's API and returns a JSON object. Due to ...

Enlist partial components in express-handlebars

I'm having trouble registering partials in my app. Despite trying various solutions from other sources, nothing seems to work for me... I have set up the express handlebars as follows: import { engine } from 'express-handlebars'; const __fi ...

Screen white on the right side

I am encountering an issue where my screen shows white on the side when I scroll to the right. I am unsure how to remove it and cannot locate the problem in the code. Here is a link to the code: https://jsfiddle.net/y3j01hbt/ In the provided code, there i ...

Minify and group options available for asset managers specifically designed for traditional HTML websites

My primary focus is on working with the CakePHP framework and utilizing a fantastic plugin that minifies and groups selected assets into a single file, reducing the number of HTTP requests needed for the entire site. Currently, I am collaborating with des ...

I am interested in rotating the yAxes scaleLabel in Angular using Chart.js

I have a vertical chart that I want to rotate horizontally. Unfortunately, there are no maxRotation and minRotation parameters for the yAxes, so I'm unsure of how to achieve this rotation. Although I found a similar question, I struggled to implement ...

$filter is functioning correctly, however it is generating an error message stating: "Error: 10 $digest() iterations reached. Aborting!"

Here is an example of a JSON object that I am working with: { "conversations":[ { "_id": "55f1595d72b67ea90d008", "topic_id": 30, "topic": "First Conversation", "admin": "<a href="/cdn-cgi/l/e ...

Enhance Fullcalendar by incorporating an HTML tag alongside the "titleformat" option

I am utilizing the jQuery Fullcalendar agenda feature. My main objective is to link an action with each date that appears in the calendar and enable the opening of a separate window for each date. Therefore, I am looking to include a button or a link next ...

Gather information from a customizable Bootstrap table and store it in an array

Currently, I have a bootstrap table configured with react-bootstrap-table-next, enabling users to edit cells and input their desired values. After completing the editing process, individuals can click on the "Submit" button to save the table values, which ...

How can I create a jumping animation effect for my <li> element in JQuery?

I have a horizontal navigation bar with a "JOIN" option. My goal is to make the #jump item continuously jump up and down after the page has finished loading. Currently, I have this code which only triggers the jump effect once when hovering over the eleme ...

Error message displayed: MUI Textfield does not support input of decimal values

I have a textfield where users can enter the unit price const [unitPrice, setUnitPrice] = useState(0); <TextField label="Unit Price" variant="outlined" margin="normal" value={unitPrice.toString ...

Creating dynamic and engaging videos using Angular with the ability to make multiple requests

I am facing an issue while working with videos in Angular. I am fetching the video URLs from an API to embed them in my application using the sanitazer.bypassSecurityTrustResourceUrl function provided by Angular. The videos are being displayed correctly wi ...

The clickable area on JQuery Tabs is not covering the entire surface

I'm having an issue with my JQuery tabs where the tab link does not work unless the mouse is directly over the text of the tab. It seems like the "li" element is being recognized instead of the link itself. I've searched for solutions, but most e ...

Manipulating HTML content with Javascript Array

Is there a way to retain Javascript context from an array? Any suggestions for improving this code? SAMPLE: <html> <script type="text/javascript"> var rand = Math.floor(Math.random() * 6) + 1; var i = Math.floor(Math.random() * 6) + 1; var ...

Utilizing NodeJS to Refine JSON Data

I am working with a JSON array that consists of multiple objects. My goal is to retrieve objects that have a specific value, such as returning [ service_wog: { count: 48, popular: false, code: 33, price: 20, id: ...