What is the best way to ensure that my button only reveals the corresponding div in its group upon clicking?

Currently, when I click the first button, both hidden divs are showing. I want it so that when I click the first button, only the hidden div in its group is shown. Similarly, when I click the second button, only the hidden div in its group is shown.

Can someone assist me in achieving this?

$(document).ready(function () {
    $(".btn").on("click", function () {
        $(this).siblings(".hidden").toggleClass("active");
    });
        
    $(".closed").on("click", function (){
        $(this).closest(".hidden").removeClass("active")
    })
})
.btn {
  background: blue;
  color: #ffffff;
  font-weight: 600;
  padding: 20px;
}


.hidden {
  width: 100px;
  height: 100px;
  background: yellow;
  display: none;
}


.hidden.active {
  display: block;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="container">
  <div class="con">
      <div class="btn">Show</div>
      <div class="hidden">
        <div class="closed">Click to hide</div>
      </div>
  </div>
</div>

<br>

<div class="container">
  <div class="con">
      <div class="btn">Show</div>
      <div class="hidden">
        <div class="closed">Click to hide</div>
      </div>
  </div>
</div>

Answer №1

Your solution

$(".hidden").addClass("active");

Targets all elements with the class .hidden (this is the root of the problem).

When handling the click event, it is important to use this to access the clicked element, then utilize DOM traversal to locate the desired element.

In this specific scenario, the desired element is the next sibling, so .next() method should be used for showing, while hiding/closing will require identifying the parent with the class .hidden

$(document).ready(function () {
    $(".show").on("click", function () {
        $(this).next().addClass("active");
    });
    
    $(".close").on("click", function (){
        $(this).closest(".hidden").removeClass("active")
    })
})
.show {
  background: blue;
  color: #ffffff;
  font-weight: 600;
  padding: 20px;
}


.hidden {
  width: 100px;
  height: 100px;
  background: yellow;
  display: none;
}


.hidden.active {
  display: block;
}

.close { background-color:#ccc; }
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="container">
  <div class="con">
      <div class="show">Show</div>
      <div class="hidden">
        <div class="close">Click to hide</div>
      </div>
  </div>
</div>

<br>

<div class="container">
  <div class="con">
      <div class="show">Show</div>
      <div class="hidden">
        <div class="close">Click to hide</div>
      </div>
  </div>
</div>

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

Checking if children have certain text using jQuery

My task involves filtering an HTML table. In order to accomplish this, I have created an 'each' callback for all 'tr' elements and check if any of their children contain a specific pattern. $("#filter").keypress(function() { var fi ...

Having trouble with JQuery's $.post function not functioning on your web server?

I'm encountering an issue with my script that uses Ajax to send a request to my PHP file for updating a txt file. Interestingly, the script works perfectly fine on my localhost but fails to work on the webserver. Testing HTML code: <!DOCTYPE html ...

Troubleshooting chained select boxes using jQuery, PHP, and database integration

Although many chained selects are typically done using JSON, I prefer to utilize my database for this purpose. However, I seem to be encountering an issue where the second select box is not loading properly. Instead of displaying the expected content, it&a ...

Ways to automatically divide lists into various div elements

Hey there! I currently have a list of categories on my page that is subject to change. I'm looking for assistance in creating a loop that will divide my lists into groups of 5 items per div. For example: foreach($categories as $cat) <label> ...

Optimizing CSS table styles for larger cell width

In my CSS file, I have defined the following style: .ES{ max-width:20px; word-wrap:break-word; } However, when I apply this to my table... <table border="1" cellpadding="2" class="ES" > <tr> <td><input name="rbeso" type="radio" ...

The Bootstrap navigation bar isn't displaying properly on mobile devices

Help! My Bootstrap navbar is not working properly on mobile view. The menu icon shows up but when clicked, no items are displayed. Here is the HTML code for my navbar: <header class="header_area"> <div class="main-menu"> ...

Detecting when the page is done loading in CasperJS with the help of $.ajaxStop()

During my CasperJS tests, I've relied on waitForSelector() to check if a page has finished loading, including all asynchronous AJAX requests. However, I'm interested in finding a more standard approach for waiting for page load. Is it possible to ...

Creating a unique tab spacing effect using HTML and CSS

I'm currently working on my personal website and I'm looking to create a tab-like effect (similar to word processors) for showcasing projects along with their descriptions. Here's an example layout: ReallyLong NameProject Project1 Descr ...

The AJAX request is functioning properly, however, when I attempt to click the icon within the button, a 500 internal server error is triggered

Encountering a 500 internal server error specifically when attempting to click the thumbs-up icon within the like button: <button class="submit-btn like" id='{{ $image->id }}'> <i class="far fa-thumbs-up"></i> Like </ ...

Arrange Bootstrap columns based on the available space within a loop

The content is contained within a md-8 div and generated through a PHP loop. The loop includes sections for: 1. about us 2. areas we cover 3. job board 4. candidates 5. join us 6. contact Due to the limited height of the "areas we cover" section, th ...

Ensure the checkbox is selected before triggering the JQuery AJAX request

How can I create a module that adds the price from the database to the total charges when a checkbox is checked, and display the result of the selected boxes using PHP? <script> function updateTextArea() { var allVals = []; ...

Is it possible to adjust the left property following the concealment of an element with JQuery?

My goal is to move an image element using the 'left' property after hiding a div. To achieve this, I am using JQuery's '.promise()' function. Here is my code: HTML code: <div id="outerContainer"> <div id=" ...

Organize the Div elements in the form of a message

Here is the code I am working with: https://jsfiddle.net/bdqgszv5/1/ This is the same code without jsfiddle: <section id="aussteller" class="row separated"> <div class="section-header text-center"> <h2& ...

Arranging adjacent div blocks to maintain alignment in a stylish way

I am facing an issue with divs that are placed side by side inside a table. These divs have been styled to appear as colored blocks. Everything seems fine when the text within each div fits on two lines, however, if it overflows onto another line, the en ...

What is the best way to send form values to the server using Ajax and Jquery?

Is there a smart way to utilize Ajax and jQuery for sending all input values from a dynamically generated form to the server? Manually listing each input name in the Ajax post seems cumbersome, so I'm wondering if there's a more elegant solution? ...

Using a for loop in JavaScript to fetch and display a specified number of results from an API

Recently, I delved into the world of Javascript and API arrays to grasp the concept of retrieving and manipulating various APIs. The topic of Javascript loops and arrays has been discussed numerous times, both here on StackOverflow and on other platforms. ...

Jquery Ajax is failing to transmit the authorization header

Attempting to set up basic authentication using Jquery Ajax. Adding an authorization header to the ajax request as shown below. $.ajax({ headers: { "authorization": "basic 123456", }, crossDomain: true, type: "POST", contentTyp ...

Retrieving information from controller to HTML page in AngularJS

Check out my code on Plunkr: http://plnkr.co/edit/8sBafktFzFa8fCLLJgMF This is the JavaScript file: angular.module('ui.bootstrap.demo', ['ui.bootstrap']); angular.module('ui.bootstrap.demo').controller('ModalDemoCtrl&ap ...

Is it possible to make the li elements within my ul list display on multiple lines to be more responsive?

My credit card icons are contained within a ul. I have used the properties background-image and display:inline for the LIs, which display nicely on larger screens. Unfortunately, when viewed on mobile devices, the icons are cut off. My question is whether ...

Working with Ext JS: Dynamically adjusting panel size when the browser window is resized

I am facing an issue with a side panel in Ext.js. Everything is working fine until I resize the browser, at which point some components of the panel get cut off. https://i.sstatic.net/eaEGI.png Is there a way to make the panel resize automatically when t ...