Reset all divs to their default state except for the one that is currently active using jQuery

Here's the plan for my script:

Once a user clicks on a "learn more" button, it will reveal the relevant information in the corresponding box.

I'm aiming to implement a feature where if you click on another "learn more" button while one box is already open, the first box automatically closes. This way, only one box can be open at a time on the page.

$(document).ready(function(){ 


 var service = $(".service"), text = $(".service-text, h1.service-heading"), moretext = $(".more-text"); 


$(".learn").toggle(
               function()
               {
                $(this).parent().find(service).animate({ backgroundColor : "#000000" }, 800);
                $(this).animate({ backgroundColor : "#FFFFFF" }, 800);
                $(this).parent().find(text).animate({ color: "#FFF"}, 800);
                $(this).parent().find("span.more").animate({ color : "#000000" }, 800, function () {
                    $(this).parent().parent().find(".service").animate({ height : "500px"}, 800, function () {
                            $(this).find(moretext).show().animate({ color: "#FFFFFF"}, 800);

                            $(this).parent().find("span.more").animate({ color : "#FFF"}, 800, function () {
                                                                                                         $(this).hide();
                                                        $(this).parent().find("span.less").show( function () {
                                                                                                           $(this).animate({ color: "#000000"}, 800);
                                                                                                         });
                                                                                                         });
                                                                                                           });
                                                                                                 });
               },
               function()
               {
                $(this).parent().find(service).animate({ backgroundColor : "#FFFFFF" }, 800, function () {
                            $(moretext).animate({ color: "#FFFFFF"}, 800, function () {
                                                                                    $(this).hide();
                                                                                                       });
                             });
                $(this).animate({ backgroundColor : "#000000" }, 800);
                $(this).parent().find(text).animate({ color: "#000000"}, 800);
                $(this).parent().find("span.less").animate({ color: "#FFFFFF"}, 800, function() {
                    $(this).parent().parent().find(service).animate({ height: "180px"}, 800, function () {
                                        $(this).parent().find("span.less").animate({ color: "#000000"}, 800, function () {
                                                                                                                       $(this).hide();
                                                            $(this).parent().find("span.more").show( function () {
                                                                                                           $(this).animate({ color: "#FFFFFF"}, 800);
                                                                                                                       });
                                                             });
                                                                                                       });
                                                                                              });





                   });
   });

Answer №1

One way to achieve this is by implementing the following code:

$(".learn").click(function(){
    $(".learn").not(this).doSomeThing(/* insert some code here */);
});

This code allows you to remove the current clicked item from the specified set.

Answer №2

Steps to improve toggle functionality:

  • Assign a unique class name to all relevant div elements
  • Move the "close" function to a separate block of code at the end of the toggle method, ensuring it does not affect divs with the class "active"
  • Create an event listener for clicking on "learn more" buttons that adds the class "active" to the clicked element, then executes the close function on all other divs before proceeding with its intended action

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 issues can be found in this piece of JQuery script?

<script src = "https://ajax.googleapis.com/ajax/libs/jquery/1.6.4/jquery.min.js"></script> <script type="text/javascript"> //waiting for the document to be ready $(document).ready(function() { ...

Establishing a link between numerous web browsers solely through client-side technology

After creating a compact AJAX-powered chat application, I wonder if it is feasible to handle all the communication client-side. Can individual pages recognize each other and share real-time updates without involving the server? Is there a way to achieve th ...

Navigating to a different page using the browser address bar causes the context to be reset

Upon receiving the user's data from the API on the login page, it is set in the user context. Subsequently, upon redirection to the AdminPanelApp, the data within the user context is displayed accurately. However, if I am in the AdminPanelApp and navi ...

What is the process of utilizing a <li> for a hover selector in jquery?

I've encountered an issue with a list that I am trying to modify its content when hovering over them. Despite using the id as a selector for triggering the hover function, all list items change color instead of just the intended one. The challenge lie ...

Styling Process Steps in CSS

Just starting out with CSS! I'm looking to replicate the Process Step design shown in the image. https://i.stack.imgur.com/Cq0jY.png Here's the code I've experimented with so far: .inline-div{ padding: 1rem; border: 0.04rem gray ...

Reliable selection menu for changing fields

Can someone help me with this coding issue? I am attempting to create a dependent dropdown menu where selecting a category will also display relevant equipment. However, in my current setup, only the category field is functioning properly. When I try to a ...

Tips for creating animations with JavaScript on a webpage

I created a navigation bar for practice and attempted to show or hide its content only when its title is clicked. I successfully toggled a hidden class on and off, but I also wanted it to transition and slide down instead of just appearing suddenly. Unfort ...

Steps for aligning an image and text within an icon next to each other

I'm looking to align a small PNG image next to some text within an icon. How can I achieve this? Currently, they are stacked vertically. Here is the current layout - I want the two elements side by side instead. The structure of the division is unique ...

How about using JQuery to smoothly fade in and out?

I've been trying to figure this out for hours $('#position-name').html('Successfully Changed').fadeOut(1000); $('#position-name').html('New Name').fadeIn(); While it seems simple, I can't understa ...

The functionality of Access-Control-Allow-Origin is not effective in Chrome, yet it operates successfully in Firefox

I'm facing an issue with my code in the HTML file. I have a second file that I want to load content from, and both files are located in the same directory <div id="mainMenu"></div> <script> $(function() { $('#mainMe ...

Guide to setting the order of rendering in React applications

I am currently working with a .tsx file that renders two components: export default observer(function MyModule(props: MyModuleProps) { .... return ( <div> <TopPart></TopPart> <LowerPart>< ...

Dealing with form submission issues in jQuery and jqGrids

Lately, I've been experimenting a lot with jqgrids and have almost everything set up the way I want it - from display to tabs with different grids. Now, I'm trying to utilize Modals for adding and editing elements on my grid. The issue I'm ...

Guidelines for automating button click using selenium in Python

<div class="wrapper"> <button class="w-full h-14 pt-2 pb-1 px-3 bg-accent text-dark-1 rounded-full md:rounded select-none cursor-pointer md:hover:shadow-big focus:outline-none md:focus:bg-accent-2 md:focus:shadow-small "> ...

Retrieve information from a database in real-time using Ajax without needing to set a refresh interval

Currently, I have been working on jquery/ajax requests and have managed to create an ajax request that retrieves data from a database. However, the issue at hand is that I am continuously utilizing window.setInterval() to refresh this function every x seco ...

Looking for a way to assign the object value to ng-model within a select tag from an array of objects? Also, curious about how to easily implement filters on ng-options?

Here is the HTML code for creating a question template: <body ng-controller="myCtrl"> {{loadDataSubject('${subjectList}')}} {{loadDataTopic('${topicList}')}} <h1 class = "bg-success" style="color: red;text-align: ...

Selecting an entire row in a Kendo grid

Is there a way to configure kendoGrid to highlight the entire row when clicked on? I have tried setting: scrollable: { virtual: true } and disabled paging, but it doesn't seem to work as intended. You can view an example here: Kendo UI Dojo When ...

What steps should I follow to have my edit form component extract values from HTML in Angular?

I created a detailed listing page that includes a picture URL, title, phone number, description, and price. When the user clicks on the Edit button, it redirects them to a page with input forms for each of these fields. The form automatically populates the ...

Using the -webkit-box-reflect property along with the CSS position:absolute styling

Running on the Chrome Canary build, I have come across this HTML code snippet: <div id="debug" class="debug" >TEST</div> Additionally, here is the CSS code snippet: -webkit-box-reflect: below 0px -webkit-gradient(linear, ...

Can you explain the inner workings of the provided code in a step-by-step manner?

I stumbled upon this code snippet that checks if the number of occurrences of an element in an array is greater than a specified value, and if so, it will remove the number: function deleteNth(arr,x) { var cache = {}; return arr.filter(function(n) { ...

What is the process for creating a custom hook in React.js/Next.js?

I encountered a problem while trying to create a hook from my code. Here is the snippet from the hook file: import { useRouter } from "next/router"; const useCurrentPath = () => { const { asPath, locale, defaultLocale } = use ...