How can I implement a jQuery slide down effect for a specific individual instance?

Whenever I click on the "Share your thoughts" button, the comments block slides down for every section instead of just the particular section I clicked on. Is there a way to make it so that only a single block slides down when the button is clicked, regardless of how many sections are on the page? Below is a snippet of my code. I am dynamically creating all the sections using PHP, resulting in 10-15 sections on the page. However, when I click on a specific section's button, the comments block slides down for every section. Is it possible to adjust the code so that only one block slides down at a time?

$('.down').click(function () {

    // Set the effect type
    var effect = 'slide';

    // Set the options for the effect type chosen
    var options = { direction: 'up' };

    // Set the duration (default: 400 milliseconds)
    var duration = 700;
     

  $('.card').toggle(effect, options, duration);
});
#comments{
       background-color: #535d92;
       display: none;
       height:60px;
           }

#slide {
    width: 90%;
    margin-top: 14px;
    margin-left: 14px;
z-index:1;
    border: none;
border-radius: 2.5em;
background: #fff;
-webkit-appearance: none; 
    outline:none;
padding: 0.85em 1.5em;
height:10%;
         }

.cd-container {
       width: 90%;
       margin: 0 auto;
               }

.post-footer ul {list-style:none}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="http://code.jquery.com/ui/1.10.4/jquery-ui.js"></script>
<div class="container">
  <section class="cd-container">
   <div class="cd-timeline-content">
    <h3>raghav</h3>
<p>Lorem ipsum dolor sit amet, consectetur                         adipisicing elit.</p>
<div class="post-footer">
<ul>
<li class="down"><a href="#">Share your thoughts</a></li>
</ul>
</div>
</div><br/>
<div id="comments" class="card">
<input type="text"  id="slide" placeholder="Hit Enter to            Send!" class="boom"/>
       </div>
  </section> <!-- cd-timeline --><br> 

 <section class="cd-container">
  <div class="cd-timeline-content">
    <h3>sharad</h3>
<p>Lorem ipsum dolor sit amet, consectetur                         adipisicing elit.</p>
<div class="post-footer">
<ul>
<li class="down"><a href="#">Share your thoughts</a></li>
</ul>
    </div>
</div><br/>
<div id="comments" class="card">
    <input type="text"  id="slide" placeholder="Hit Enter to           Send!" class="boom"/>
</div>
 </section>
</div>

Answer №1

  1. Ensure that the .card is only activated within the same section as the clicked share your thoughts element by following these steps:

    Replace

     $('.card').toggle
    

    with

    $(this).parents('section.cd-container').find('.card').toggle
    
  2. To address dynamic sections, such as those loaded after page load using ajax, modify the click event to delegate to the container element or document. Follow this procedure:

    Replace

    $(".down").click(function() {
    

    with

    $(".container").on("click", ".down", function() {
    
  3. Note that having multiple elements with id="comments" in your HTML is not valid, as IDs must be unique. Consider changing it to a class and updating the css accordingly.

VIEW WORKING EXAMPLE HERE:

$(".container").on("click", ".down", function() {

  // Set the effect type
  var effect = 'slide';

  // Set the options for the effect type chosen
  var options = {
    direction: 'up'
  };

  // Set the duration (default: 400 milliseconds)
  var duration = 700;

  $(this).parents('section.cd-container').find('.card').toggle(effect, options, duration);
});
#comments {
  background-color: #535d92;
  display: none;
  height: 60px;
}
#slide {
  width: 90%;
  margin-top: 14px;
  margin-left: 14px;
  z-index: 1;
  border: none;
  border-radius: 2.5em;
  background: #fff;
  -webkit-appearance: none;
  outline: none;
  padding: 0.85em 1.5em;
  height: 10%;
}
.cd-container {
  width: 90%;
  margin: 0 auto;
}
.post-footer ul {
  list-style: none
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="http://code.jquery.com/ui/1.10.4/jquery-ui.js"></script>
<div class="container">
  <section class="cd-container">
    <div class="cd-timeline-content">
      <h3>raghav</h3>
      <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit.</p>
      <div class="post-footer">
        <ul>
          <li class="down"><a href="#">Share your thoughts</a>
          </li>
        </ul>
      </div>
    </div>
    <br/>
    <div id="comments" class="card">
      <input type="text" id="slide" placeholder="Hit Enter to            Send!" class="boom" />
    </div>
  </section>
  <!-- cd-timeline -->
  <br>

  <section class="cd-container">
    <div class="cd-timeline-content">
      <h3>sharad</h3>
      <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit.</p>
      <div class="post-footer">
        <ul>
          <li class="down"><a href="#">Share your thoughts</a>
          </li>
        </ul>
      </div>
    </div>
    <br/>
    <div id="comments" class="card">
      <input type="text" id="slide" placeholder="Hit Enter to           Send!" class="boom" />
    </div>
  </section>
</div>

Answer №2

It is advisable to locate the parent element and search for the comment section.

$(document).on('click', '.down', function () {
    //locate the parent
    var $parent = $(this).parents('.cd-container');    

    // Specify the effect type
    var effect = 'slide';

    // Define options for the chosen effect type
    var options = { direction: 'up' };

    // Set the duration (default: 400 milliseconds)
    var duration = 700;

    $parent.find('.card').toggle(effect, options, duration);
});



The click handler has been modified as well, since the way it was originally bound would only work for elements loaded on page load, not dynamically added ones. It is also recommended to use .on('click') instead of .click().

$(document).on('click', '.down', function() {
     //code 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

Is it possible to map through material-ui components within an array in React.js?

I've been attempting to implement material-ui and iterate over it within an array (to create ratings for items, similar to e-commerce websites). Unfortunately, the code is not functioning as expected. When I run it on my localhost server, no stars are ...

Make sure to concentrate on the input field when the DIV element is clicked

In my React project, I am working on focusing on an input element when specific buttons or elements are clicked. It is important for me to be able to switch focus multiple times after rendering. For instance, if a name button is clicked, the input box for ...

Problem with alternating row colors in my table

Trying to add some style to my table on the webpage by alternating row colors, but I'm running into some issues. I've followed tutorials and tried using different CSS selectors like nth-of-type(even), nth-of-type(2n+0), and nth-of-type(odd). Howe ...

Is there a way to modify the color of my question post-submission?

Within my code, there are numerous queries that need to be addressed. Upon submission, I desire to alter the color of each question to green if the response is correct, or red if it is incorrect. document.getElementById("submit-button").addEventLi ...

Using Javascript to place a form inside a table

When attempting to add a Form inside a Table, only the input tags are being inserted without the form tag itself. $(function () { var table = document.getElementById("transport"); var row = table.insertRow(0); var cell1 = row.insertCell(0); ...

Express.js Failing to Send Response Following POST Request

This is the function I have on the back end using express: // Function to register a new user exports.register_user = function(req, res) { var portalID = req.body.portalID; var companyName = req.body.companyName; var password = req.body.passwo ...

Converting an HTML table into an Excel spreadsheet

In the process of developing an application that populates a table based on a JSON dataset, I am seeking a way to store the filtered data into an Excel file or even a CSV. The structure includes two script files - app.js and mainController.js (organized fo ...

Encountering difficulties with the functionality of Google Places API

I am attempting to incorporate the autocomplete functionality of Google Places API into a text field. Below is the code I have implemented: <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"> </script> <script ...

Dealing with ng-repeat and button alignment across Chrome, Edge, and Firefox

Can someone help me understand this strange behavior I am experiencing across all browsers? <div style="margin-top:5px"> <button translate="clear" ng-click="xyz.clear()" class="btn btn-default"></button> <butt ...

Ways to apply CSS to a changing div ID

I am looking to apply CSS to a dynamically generated div ID. var status = var status = item.down().next().innerHtml(); if(status == "test") { var c = 'item_'+i ; c.style.backgroundColor = 'rgb(255, 125, 115)'; //'ite ...

A solitary block positioned at the heart of a grid - jquery mobile

Using grid in jQuery Mobile, I have designed a page and now looking to place a block exactly centralized on it. In the first grid, there are 2 blocks equally positioned. In the next grid, only one block is present and I want it to be centered. JSFiddle L ...

JavaScript code for iframe auto resizing is not functioning properly on Firefox browser

I have implemented a script to automatically resize the height and width of an iframe based on its content. <script language="JavaScript"> function autoResize(id){ var newheight; var newwidth; if(document.getElementById){ newh ...

What is the best way to separate two <a> tags using only Bootstrap?

Currently, I am utilizing a PHP for loop to display 10 tags on an HTML page. My challenge lies in wanting the <a> tags to be displayed on separate lines with some spacing. It's common practice to handle this through custom CSS, however, is ther ...

Incorporating HTML into the Ajax Response

I recently encountered a strange issue with a service that returns an HTML page as the AJAX response. This page contains a form that is automatically triggered by scripts within the page, resulting in a POST request being sent when the page is rendered. My ...

Creating responsive divs on my webpage

Although I have browsed through various posts with similar questions, none of the solutions seem to work for me. I will make sure to include all relevant information related to my issue and explain why I am unable to resolve it on my own. Currently, I am ...

The Safari browser is unable to provide the country name in the geolocation response

My geolocation feature for displaying country names is functional in Chrome and Firefox, but not in Safari. How can I troubleshoot this issue? Javascript: $.get("http://freegeoip.net/json/", function (response) { $("#ip").html("IP: " + response.ip); ...

Using the ico-moon icon in an HTML email for various email clients such as Outlook and Gmail

I would greatly appreciate it if someone could provide instructions on how to incorporate ico-moon icons into an email HTML, ensuring they can be properly displayed in various email clients such as Outlook and Gmail. ...

Addressing an error of "call stack full" in nextjs

I am currently working on a project in nextjs where I need my billboard to continuously scroll to show different information. The Nextjs debugger keeps showing me an error message that says 'call stack full'. How can I resolve this issue? con ...

The button should only be visible when the input is selected, but it should vanish when a different button within the form is

Having an issue with displaying a button when an input field is in focus. The "Cancel" button should appear when a user interacts with a search bar. I initially used addEventListener for input click/focus to achieve this, but ran into a problem: on mobile ...

Implementing Jquery: Show a class after clicking the button and then remove it

I am looking for a way to display a class when a button is clicked and then remove it when the same button is clicked again, repeatedly. I have multiple buttons so I cannot use the toggle function as it does not provide the desired behavior. I have tried v ...