Switch the text display by clicking on a different button in the list

I am currently dealing with an issue involving a list of boxes containing text/images and buttons for expanding/collapsing the text. Whenever I click on another item's button, the text box that was previously opened gets closed, but the button text remains unchanged at "More details."

For a visual representation of the problem, you can visit

In the screenshot provided, you can see the sequence of events leading to the issue. When I clicked on the second item's button and then the first item's button, the text box closed without the button text changing back to "more details" (más detalles).

https://i.sstatic.net/Xichs.png

   
                $("document").ready(function(){
                    $(".btn1").click(function() {
                        if ($.trim($(this).text()) === 'Más detalles') {
                            $(this).text('Menos detalles');
                        } else {
                            $(this).text('Más detalles');
                        }
                        
                        var $p1 = $(this).next(".p1");
                        var $p1img = $(this).parents().eq(4).find(".p1-img");
                      
                        $p1.toggle();
                        $p1img.toggle();
                      
                        $(".p1").not($p1).hide();
                        $(".p1-img").not($p1img).hide();    
                    });
                });
.p1, .p1-img {
                display: none;
            }
  
                <!DOCTYPE html>
                <html lang="en">
                <head>
                    <meta charset="UTF-8">
                    <meta name="viewport" content="width=device-width, initial-scale=1.0">
                    <meta http-equiv="X-UA-Compatible" content="ie=edge">
                    <title>Document</title>
                    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
                </head>
                <body>
                    <div id="event-56092" class="ect-list-post ect-featured-event data-parent-post " id=" 56053">
                        <div class="ect-list-post-left ">
                            <div class="ect-list-img" style="background-image:url('https://www.lagaleramagazine.es/wp-content/uploads/2019/01/50008823_1936412149789348_6701274349090897920_n-1024x715.jpg');background-size:cover;background-position:center center;">
                                <a href="https://www.lagaleramagazine.es/agenda/vi-escuelas-deportivas-para-mayores/2019-02-25/" title="Imagen del evento" alt="Magazine 1" rel="bookmark">
                                    <div class="ect-list-date">
                                        <div class="ect-date-area default-schedule">
                                            <span class="ev-day">25</span>
                                            <span class="ev-mo">febrero</span>
                                            <span class="ev-yr">2019</span>
                                        </div>
                                    </div>
                                </a>
                            </div>
                        </div>
                        <div class="ect-list-post-right">
                            <div class="ect-list-post-right-table">
                                <div class="ect-list-description">
                                    <h2 class="ect-list-title">
                                        <a class="ect-event-url" href="https://www.lagaleramagazine.es/agenda/vi-escuelas-deportivas-para-mayores/2019-02-25/" title="VI Escuelas Deportivas para Mayores" rel="bookmark">VI Escuelas Deportivas para Mayores</a>
                                    </h2>
                                    <button class="btn1 button-more svg" >Más detalles</button>
                                    <div class="p1" style="display: none;">
                                        <div class="ect-event-content">
                                            <p>Desde el lunes 21 de enero y hasta el martes 18 de junio, todos los socios de los Centros Municipales de Mayores que participan en la XXIII Campaña de Atención al Mayor, podrán inscribirse en las diferentes actividades de la VI Escuelas Deportivas para mayores. Se impartirán clases de pádel, tenis de mesa, petanca, rutas...</p>
                                            <a href="https://www.lagaleramagazine.es/agenda/vi-escuelas-deportivas-para-mayores/2019-02-25/" class="ect-events-read-more" rel="bookmark">Ir al evento »</a>
                                        </div>
                                    </div>
                                </div>
                                <div class="p1-venue">
                                    <div class="ect-list-venue default-venue">
                                        <span class="ect-icon">
                                            <i class="fa fa-map-marker" aria-hidden="true"></i>
                                        </span>
                                        <span class="ect-venue-details ect-address">
                                            <a href="https://www.lagaleramagazine.es/lugar/area-de-atencion-al-mayor-ayuntamiento-de-badajoz/" title="Area de atención al Mayor , Ayuntamiento de Badajoz">Area de atención al Mayor , Ayuntamiento de Badajoz</a>,
                                            <span class="tribe-address">
                                                <span class="tribe-locality">Badajoz</span>
                                                <span class="tribe-delimiter">,</span>
                                                <abbr class="tribe-region tribe-events-abbr" title="Badajoz">Badajoz</abbr>
                                                <span class="tribe-country-name">España</span>
                                            </span>
                                        </span>
                                        <span class="ect-google">
                                            <a class="tribe-events-gmap" href="https://maps.google.com/maps?f=q&amp;source=s_q&amp;hl=en&amp;geocode=&amp;q=Badajoz+Badajoz+Espa%C3%B1a" title="Click para ver mapa de Google" target="_blank">+ Google Map</a>
                                        </span>
                                        <div class="ect-rate-area">
                                            <span class="ect-rate-icon">
                                                <i class="fa fa-money" aria-hidden="true"></i>
                                            </span>
                                            <span class="ect-rate">Gratuito</span>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                </body>
            </html>

Answer №1

To tackle this issue effectively, modify the text content of other .btn1 elements in a manner similar to how you conceal additional elements with classes .p1-img. This process can be streamlined using:

$(".btn1").not(this).text('More details');

immediately after

$(".p1-img").not($p1img).hide();

as illustrated below:

$("document").ready(function(){
    $(".btn1").click(function() {
        if ($.trim($(this).text()) === 'More details') {
          $(this).text('Less details');
        } else {
          $(this).text('More details');
        }
        
        var $p1 = $(this).next(".p1");
        var $p1img = $(this).parents().eq(4).find(".p1-img");
      
        $p1.toggle();
        $p1img.toggle();
      
        $(".p1").not($p1).hide();
        $(".p1-img").not($p1img).hide();
        $(".btn1").not(this).text('More details');
        
      });
});
.p1, .p1-img {
    display: none;
  }
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8>
    <meta name="viewport" content="width=device-width, initial-scale=1.0&
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <link rel="stylesheet" href="details.css">
    <script src="details.js"></script>
</head>
<body>
    <div id="event-56092" class="ect-list-post ect-featured-event data-parent-post " id=" 56053">;
        <div class="ect-list-post-left ">;
            <div class="ect-list-img" style="background-image:url('https://www.lagaleramagazine.es/wp-content/uploads/2019/01/50008823_1936412149789348_6701274349090897920_n-1024x715.jpg');background-size:cover;background-position:center center;">;
                <a href="https://www.lagaleramagazine.es/agenda/vi-escuelas-deportivas-para-mayores/2019-02-25/" title="Event Image" alt="Magazine 1" rel="bookmark">;
                    <div class="ect-list-date">;
                        <div class="ect-date-area default-schedule">;
                            <span class="ev-day">25</span> ;
                            <span class="ev-mo">February</span> ;
                            <span class="ev-yr">2019</span>;
                        </div>;
                    </div>;
                </a>;
            </div>;
        </div>;
        <div class="ect-list-post-right">;
            <div class="ect-list-post-right-table">;
                <div class="ect-list-description">;
                    <h2 class="ect-list-title">;
                        <a class="ect-event-url" href="https://www.lagaleramagazine.es/agenda/vi-escuelas-deportivas-para-mayores/2019-02-25/" title="VI Escuelas Deportivas para Mayores" rel="bookmark">VI Senior Sports Schools</a>;
                    </h2>;
                    <button class="btn1 button-more svg">More details</button>;
                    <div class="p1" style="display: none;">;
                        <div class="ect-event-content">;
                            <p>From Monday, January 21st to Tuesday, June 18th, all members of Municipal Senior Centers participating in the XXIII Senior Care Campaign can enroll in various activities offered by VI Senior Sports Schools. Classes include paddle tennis, table tennis, petanque, excursions...</p>;
                            <a href="https://www.lagaleramagazine.es/agenda/vi-escuelas-deportivas-para-mayores/2019-02-25/" class="ect-events-read-more" rel="bookmark">> Go to event »</a>;
                        </div>;
                    </div>;
                    <br>; 
                    <br>;
                    <button class="btn1 button-more svg">More details</button>;
                    <div class="p1" style="display: none;">;
                        <div class="ect-event-content">;
                            <p>From Monday, January 21st to Tuesday, June 18th, all members of Municipal Senior Centers participating in the XXIII Senior Care Campaign can enroll in various activities offered by VI Senior Sports Schools. Classes include paddle tennis, table tennis, petanque, excursions...</p>;
                            <a href="https://www.lagaleramagazine.es/agenda/vi-escuelas-deportivas-para-mayores/2019-02-25/" class="ect-events-read-more" rel="bookmark">> Go to event »</a>;
                        </div>;
                    </div>;
                </div>;
                <div class="p1-venue">;
                       (Additional HTML code removed for brevity)
                </div>;
            </div>;
        </div>;
    </div>;
</body>;
</html>;

Note: Ensure that all toggle buttons utilized on the page are part of the .btn1 class.

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

Issue with Moment.js incorrectly formatting date fields to a day prior to the expected date

Currently, I am attempting to resolve a small issue in my code related to a tiny bug. In my React component, I have set an initial state as follows: const initialFormData = Object.freeze({ date: Moment(new Date()).format('YYYY-MM-DD'), pr ...

The functionality of Angular 2's AsyncPipe seems to be limited when working with an Observable

Encountering an Error: EXCEPTION: Unable to find a support object '[object Object]' in [files | async in Images@1:9] Here's the relevant part of the code snippet: <img *ngFor="#file of files | async" [src]="file.path"> Shown is the ...

Why do query values disappear when refreshing a page in Next.js? [Illustrative example provided]

In my current project, I am developing a simple Next Js application consisting of just two pages. index.tsx: import React from "react"; import Link from "next/link"; export default function Index() { return ( <di ...

Using CSS to style an alternate list elements to float

I'm working on a webpage that displays messages from a database using ajax. Currently, the output is just stacked downwards. I'm hoping to style the list elements to alternate from left to right, similar to an iOS Message chat. Does anyone have ...

How to Use a Discord Bot to Send a Message (Step-by-Step Guide)

I am looking for a simple way to send a message using my discord bot, but everything I have found online seems too complex for me to understand and implement. require("dotenv").config(); //to start process from .env file const { Client, GatewayIn ...

Gather information from HTML elements that are updated with text dynamically via AJAX calls using Scrapy

My goal is to extract information about mobile phones listed on the 'amazon.in' website from the following link: here using scrapy. Below is the code I am using: from scrapy.spiders import CrawlSpider, Rule from scrapy.linkextractors import Lin ...

Utilize React to float the Material UI SwipeableDrawer component to the right side of the screen

I'm currently working on a project that involves using material UI alongside React/Redux. There has been a recent change in the Figma file where the SwipeableDrawer component is now positioned on the right side of the screen instead of the left. I&apo ...

What could be causing these strange white lines to show up on my AFrame meshes?

When I import a GLB scene with baked textures into A-Frame using THREE.js, I am experiencing an issue where white lines appear on my objects (pictured below). The walls are grouped meshes which may explain the lines appearing there, but I am puzzled as to ...

The functionality to open the menu by clicking is experiencing issues

I'm attempting to replicate the Apple website layout. HTML structure: <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" conte ...

Is it possible to duplicate a response before making changes to its contents?

Imagine we are developing a response interceptor for an Angular 4 application using the HttpClient: export class MyInterceptor implements HttpInterceptor { public intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<an ...

Is there a way to customize the color of the active navbar item?

My navigation bar consists of 3 buttons and I'm looking to customize the text color for the active page. Additionally, I want to set a default button which is the first one in the list. I attempted using StyledLink from another solution but it doesn& ...

What steps should I take to make jQuery compatible with a Greasemonkey 0.8 script on Firefox 2, without internet access on the computer?

Currently using Firefox 2.0.0.11, Greasemonkey 0.8.x, and the latest version of jQuery (1.3.2) that is compatible with Greasemonkey 0.8. Attempting to load this Userscript: // ==UserScript== // @name TEST // @include * // @require jquery. ...

Can a library be developed that works with both Java and JavaScript/TypeScript?

I specialize in Angular development. Our front- and backend both contain specialized calculation methods that work like magic. Although the classes are the same, any bugs found in the calculations have to be fixed separately in two different projects. Is ...

Tips for designing a search bar using Angular

search : ____________ I am interested in designing a search bar functionality that automatically triggers when the user inputs 8 or more characters. The input text will be stored in a variable, the search bar will be reset, and the backend API will be che ...

Learn how to create a registration form using Ajax, PHP, and MySQL

So far I've been working with HTML <form id="account_reg" action="reg.php" method="post"> <div id="response"></div> <div class="input"> <label>Login</> <input name="login" type="text" class=" ...

Encountering yet another frustrating issue with z-index not functioning properly in versions of IE above 7, despite extensive research yielding no solution

I have scoured numerous resources and read countless articles on how to resolve z-index issues in IE 7, 8, and 9. However, none of the suggested solutions seem to work for my particular situation. The issue at hand is that I have interactive content posit ...

Organize a collection of objects based on their individual keys

How can an array of objects be grouped based on keys using vanilla JavaScript, especially when dealing with a large number of records like 10000? Here is a sample object to illustrate: [ { company: "TATA", car: "TATA Indica", color: "Blue" }, { ...

Combining Blazor with Bootstrap for seamless form validation

After gaining some experience with Razor, I decided to explore Blazor. However, I encountered a familiar challenge - integrating validation with Bootstrap. The issue lies in the mismatch between Blazor's validation result classes and those of Bootstra ...

Utilizing Multiple Carousels on a Single Bootstrap 5 Page

I am facing a challenge in making multiple Bootstrap carousels work correctly on a single page. According to Bootstrap guidelines, each carousel should have a unique ID. However, I am struggling to implement this and only one carousel functions properly ...

Standardize API data for utilization in Redux

I have an API that provides the following data: const data = { id: 1, name: 'myboard', columns: [ { id: 1, name: 'col1', cards: [ { id: 1, name: 'card1' }, { id: 2, name: 'card ...