The functionality of jQuery is not functioning properly on dynamically created identical divs

I am currently working on creating a comment reply section. I have managed to load the same div for reply that I use for commenting by utilizing

$('#1').append($('.enterComment').html());
. In this case, 1 represents the id of the div that will appear when the reply option is clicked.

The .enterComment div contains a hidden submitPost button, which is designed to become visible as soon as the user begins typing a comment.

While the div is loading correctly, I am encountering an issue where, upon loading the same div in the reply section and typing in it, the hidden div only appears in the main comment section, not the reply one.

Here is the structure of my HTML:

<div class="enterComment">
      <form id="insertComment">

          <textarea name="comment" placeholder="comment here..."></textarea>

          <div id="commentOptions">
             <button type="button" class="btn btn-primary btn-sm">Comment</button>
          </div>
        </form>
    </div>

For the reply section, I have:

<ul class="commentList">
         <li>
             <div class="commentData" id="1">
                <p>The comment content will go here</p>
                <p><span class="reply">Reply</span> <i class="fa fa-thumbs-up" aria-hidden="true" tabindex="1"></i> <i class="fa fa-thumbs-down" aria-hidden="true" tabindex="1"></i> </p>
              </div>
          </li>
       </ul>

and here is the associated script:

$("body").on('focus', 'textarea', function() {
     $('#commentOptions').fadeIn(1000);
}); 

$("body").on('click', '#1 p .reply', function() {
     $('#1').append($('.enterComment').html()); 
});

Answer №1

To achieve a fade-in effect on the next div after a textarea, you can use the .next() function.

It is essential for Identifiers in HTML to be unique, so it is recommended to utilize CSS classes. In this example, the commentOptions CSS class is used.

$("body").on('focus', 'textarea', function() {
  $(this).next('.commentOptions').fadeIn(1000);
});

$("body").on('click', '.commentData p .reply', function() {
  var element = $('.enterComment').clone();
  element.find('.commentOptions').hide();
  $(this).closest('.commentData').append(element);
});
.commentOptions {
  display: none
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="enterComment">
  <form id="insertComment">
    <textarea name="comment" placeholder="comment here..."></textarea>
    <div class="commentOptions">
      <button type="button" class="btn btn-primary btn-sm">Comment</button>
    </div>
  </form>
</div>


<ul class="commentList">
  <li>
    <div class="commentData" id="1">
      <p>The comment content will go here</p>
      <p><span class="reply">Reply</span> <i class="fa fa-thumbs-up" aria-hidden="true" tabindex="1"></i> <i class="fa fa-thumbs-down" aria-hidden="true" tabindex="1"></i> </p>
    </div>
  </li>
</ul>

Answer №2

I have designed a self-contained HTML file that functions independently without any additional dependencies, except for the jQuery and Bootstrap libraries you used in your example:

<!DOCTYPE html>
<html>
<head>
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
  <style type="text/css">
    body{
      padding: 10px;
    }

    .wrapper{
      width: 800px;
      margin-right: auto;
      margin-left: auto;
    }

    .submit-comment-btn-container {
      display: none;
    }
  </style>

  <script type="text/javascript">
    $( document ).ready(function() {
      $('#comment-textarea').on('focus', function() {
        $('.submit-comment-btn-container').fadeIn('fast');
      }); 

      $('#submit-comment-btn').on('click', function() {
        var text = $('#comment-textarea').val();
        if(text != ''){
          $('.submit-comment-btn-container').fadeOut();
          $('#comment-textarea').val('');
          // cloning the first child of the comments to use as a template
          var comment = $('.comment-list').children().first().clone();
          // replacing the content of the cloned comment with the new text
          $(comment).html(text);
          // appending the new comment to the comment list
          $(comment).appendTo('.comment-list');

        }
      });
    });
  </script>
</head>

<body>
  <div class="wrapper">
    <div class="enterComment">
      <form id="insertComment">
        <div class="comment-text-container">
          <textarea id="comment-textarea" placeholder="Comment here..."></textarea>
        </div>
        <div class="submit-comment-btn-container">
          <button id="submit-comment-btn" type="button" class="btn btn-primary btn-sm">Comment</button>
        </div>
      </form>   
    </div>
    <div class="comment-list-container">
      <ul class="comment-list">
        <li>
          <div class="comment">
            Comment goes here
          </div>
        </li>
      </ul>
    </div>
  </div>
</body>
</html>

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

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 ...

ExtJS variable not populating with servlet data

I'm facing an issue with my code where I am calling a servlet from JavaScript using an AJAX request. The data from the servlet is shown in a message box within the success function, but it's not being loaded into a variable called `myData` in Jav ...

Angular Sending JSON Data via POST Request

Whenever I submit an empty form through my Angular application, the JSON being sent is as follows: {foo: {}} This causes a 500 error to occur on my server instead of the expected 422 error, since the server requires the following structure: {foo: {bar: ...

Displaying that the response from ajax is experiencing issues

I am currently attempting to update the td elements in a table but my current method is not yielding successful results. Here's what I have tried: <table id="job1"> <tr><td></td></tr> <tr id="Jobstatus1"> ...

What is the best way to divide a page into four equal sections using two container divs?

I am working on a webpage layout that requires dividing it into four equal sections. The challenge is overlapping text onto two of these sections, which complicates the design process. My solution is to stack two container DIVs on top of each other, both w ...

Discover the CSS auto height value using JavaScript

Is there a way to utilize JavaScript in determining the value set for auto height in CSS? My development stack includes Grails and jQuery. For instance, consider the following CSS: .tool-preview { height: auto; } ...

Tips on utilizing a local file as a background image URL

How can I modify my CSS to link to a local file path like C:\xampp\htdocs\Folder instead of the URL https://source.unsplash.com/1600x1050/?nature. I am currently using Bootstrap 4 and below is my CSS code: .jumbotron{ background: ...

The .push method in Javascript is failing to execute

I'm facing a challenge with this particular code snippet. Essentially, I am attempting to loop through an array of Word objects and categorize them based on word type using a switch statement. This process is triggered by jQuery listening for a button ...

Tagging photos - Displaying tagged box when hovering over a name

I am currently working on a feature where hovering over a tag name in the list will display a box at the tagged location (similar to Facebook). Below is the code I have: Viewtag.php <?php $sql = "SELECT * FROM image_tag ORDER BY `pic_id`"; $qry = mys ...

Refreshing data asynchronously with Ajax

I am currently using jQuery AJAX to retrieve a page named matid.jsp as shown below: var loadUrl = "matid.jsp"; $(".get").click(function () { $.get(loadUrl, function (responseText) { $("#result").html(responseTex ...

Can the height of an input element be set to zero?

Currently, I am utilizing CSS transitions to adjust the height of an input element from 40px to 0px in an attempt to make it disappear. While this technique works effectively for images and yields a satisfactory result, it seems to fall short when applied ...

What is the most efficient way to update a counter when a button is clicked in React and display the result on a different page?

Just delving into the world of React and Javascript, I decided to challenge myself by creating a Magic 8 Ball application. Currently, I have set up two main pages: The magic 8 ball game page A stats page to showcase information about the magic 8 ball qu ...

navigating up and down html elements using css selectors

Within my code, I have this odd repetitive HTML structure (with no classes) and I'm looking to extract all links along with the accompanying text below each link. While it's simple enough to grab all the links using a basic CSS query selector li ...

Encountered an error while attempting to insert a new user into a MySQL database using the Node, Express, and MySQL package

Currently in the process of creating a CRUD API using NodeJS. My main goal at the moment is to execute a POST request to add a new user to the database. The issue I am facing is that although I can successfully add a new user to the database, my server cra ...

Alignment issue with content within bootstrap grid

.course-card{ background: white; border-radius: 0.25rem; padding: 1rem 1rem 1rem 1rem; text-align: center; } <div class="row d-flex align-items-center course-card"> <div class="col-md-6 course-progress"> <p>test</p> ...

Create a div that pops up when clicked, just like the Fancybox jQuery feature

I'm looking to create a popup div with an elastic effect similar to jQuery's fancybox. I've tried using the following code, but it doesn't seem to work... Here is the HTML: <a href="#" id="LoginAnchorLink">ClickME</a> < ...

The specified function is not recognized within the HTMLButtonElement's onclick event in Angular 4

Recently diving into Angular and facing a perplexing issue: "openClose is not defined at HTMLButtonElement.onclick (index:13)" Even after scouring through various resources, the error seems to be rooted in the index page rather than within any of the app ...

Can the jQuery live function be triggered without the need for an event?

Using the live function in jQuery requires an event to trigger it. More information can be found in the official API documentation. $(".xyz").live('event', function(){ }); I am trying to make the above function run as soon as the dynamicall ...

I am having issues with the external CSS and JS files not functioning properly in my project

I'm currently working on a project that has the following file structure: https://i.sstatic.net/ixd9M.png However, I am facing issues with loading my CSS and JS files... <link rel="stylesheet" href="./css/main.css"> <sc ...

Is there a way to make the menu slide up from the bottom button instead of instantly appearing? Looking for solutions in HTML, CSS, and JS

I have attempted numerous methods, but the menu keeps showing up in the same way every time. I've experimented with changing the height from 0 to 20%, width from 0 to 100%, using jQuery, JavaScript, slideUp/Down, hide/Show, adjusting margin-bottom fro ...