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

Using JavaScript to invoke Applescript commands

Is it feasible to execute Applescript from JavaScript? I would be grateful if someone could offer a sample code or useful reference link. ...

Having trouble with CORS errors persisting despite configuring CORS options for Google Authentication on React/Node/Passport

Currently, I'm in the process of developing a basic application using React for the frontend and Node/Express/MongoDB for the backend. User authentication is being handled through Passport, with local authentication and Google authentication both func ...

Avoiding the need to wait for completion of the jQuery $.get function

Currently, I am executing a basic jQuery GET request as shown below and it is functioning correctly. $.get("http://test.example.com/do-something", function (data) { console.log("test work done"); }); The GET request is initiated without affecting the ...

Is it universally compatible to incorporate custom attributes through jquery metadata plugin in all web browsers?

Picture this: a fictional markup that showcases a collection of books with unique attributes, utilizing the metadata plugin from here. <div> Haruki Murakami </div> <div> <ul> <li><span id="book5" data="{year: 2011} ...

Having trouble with the JavaScript DOM rewrite for aligning text?

function modifyTextAlignment(){ document.getElementById("th1").style.textAlign = "right"; } #th1{ text-align:left; } <table> <tr><center><th colspan="2" id="th1">List of Important Emergency Contacts</th><center></tr& ...

Ensure that the loop is fully executed before proceeding with any additional code

Check out this code snippet I've been developing: let arrayB = []; for (let index = 0; index < res.length; index++) { let fooFound = false; const dynamicFoo = require(`./modules/${res[index]}`); rest.get(Routes.applicationCommands("BLA ...

Using PHP to dynamically pull and update webpage content directly from the database

Currently, I am utilizing PHP to upload information into a database and then using PHP again to display that data. In the code snippet provided below, PHP is used to exhibit all the content stored in the database. Each row within the database table will b ...

What causes Chrome to automatically remove a script tag?

Hello everyone! Instead of utilizing jQuery, I have been creating a script tag and appending it to the head tag in order to retrieve JSONP data. However, after the JSONP callback function is executed, I have noticed that the script tag that I added to the ...

The jQuery dynamic fields vanish mysteriously after being validated

I am facing an issue with my jQuery and validation. Below is the code snippet causing the problem: var fielddd = 1; $(document).on('click', '.btn.add-field', function() { fielddd++; $('#newfield').append('< ...

Having trouble with jQuery attribute selectors? Specifically, when trying to use dynamic attribute

This is the code I am working with $("a[href=$.jqURL.url()]").hide(); $.jqURL.url() fetches the current page URL. Unfortunately, this code is not functioning as expected. Is there a way to dynamically select elements? ...

What is the process for dynamically updating a variable's state within a render function?

I'm currently working on a project for my class where we are tasked with creating a website using React. Unfortunately, neither myself nor my group members have been able to figure out how to render a function in a variable state and make it dynamic. ...

Comparing two tables in jQuery/Javascript for matching data

I want to check for matches between the rows of two HTML tables, where the data in the first cell can be duplicated but the data in the second cell is always unique. The goal is to determine if the combination of values in the first and second cells of tab ...

Text overlapping image causing hover state interference

I'm feeling completely lost right now. My goal is to have the title of each project displayed in the center of the screen when you hover over the respective project images. I've resorted to using jQuery for this because it seems like the most str ...

Comparison of jQueryUI and Bootstrap button styles

Currently, I am utilizing the following libraries: bootstrap.min, jquery-1.10.2, jquery-ui-1.10.4.min. My goal is to implement a drag and drop feature using these libraries. However, I have encountered an issue where Bootstrap buttons are not draggable des ...

Is it possible to modify or delete the question mark in a URL?

Currently, I am working on implementing a search bar for one of my websites hosted on Github. Below is the code I have written for the search bar: <!-- HTML for SEARCH BAR --> <div id="header"> <form id="newsearch" method ...

Checkbox click event not triggering properly

I am facing challenges in triggering an onclick event for the "Elevation" checkboxes located at the URL provided above. <input type="checkbox" value="A" id="elevation_A" onclick="changeElevation(this.value);" /> For some reason, the "changeElevati ...

What is the best method for looping through a JavaScript object in cases where the value itself is an object?

Updated query. Thanks to @WiktorZychla for sparking my Monday morning thoughts on recursion. The revised code is functioning correctly now. Assuming I have a dummy object structured like this: const dummy = { a: 1, b: 2, c: { d: 3, ...

Obtain a specific portion of text from a string that resembles a URL

$("#index-link")[0].search = "?isNameChecked=False&isDateChecked=False&isStatusChecked=True" Is there a way to use jQuery to identify whether isStatusChecked is set to true or false in the given string? ...

Is it possible for a website administrator to view the modifications I have made to the CSS and HTML code?

Is it possible for a website to detect any temporary changes made to their CSS or Html through developer tools, even though these changes are not permanent? ...

header color scheme and dimensions

Hello, I've managed to get the menu working correctly on my website at www.g-evo.com/header.php. However, I'm now facing an issue with the size of the header. I'd like to shrink the grey area slightly so it aligns better with the logo, while ...