-6

What I am trying to do is add a commenting feature to my web application. Ideally here is the setup:

<div class="panel-footer">
    <a>Comment 1</a>
</div>
<div class="panel-footer">
    <a>Comment 2</a>
</div>
<div class="panel-footer">
    <a class="comment-add"><span class="glyphicon glyphicon-plus"></span></a>
</div>
$(".comment-add").click(function() {
    var c = "<span class='glyphicon glyphicon-plus'></span>"
    var b = "<a class='comment-add'>" + c + "</a>"
    var a = "<div class='panel-footer'>" + b + "</div>"
    $(this).parent().after(a);
});

The plus symbol will be a glyphicon that when clicked turns into an editable comment. I already have that working so for now just ignore that. The issue I'm having is that when the (+) symbol is clicked, I would like it to generate a new (+) after it that can also be click to generate another (+).

In the fiddle, you can see that the first (+) can be repetitively click to generate more (+)'s but those generated cannot be clicked.

Here is the fiddle, I feel like I'm close I am just having trouble figuring it out.

https://jsfiddle.net/DTcHh/27702/

Rory McCrossan
  • 306,214
  • 37
  • 269
  • 303
  • simple... don't replace the "add another comment" div. instead make a new comment div... – Kevin B Dec 08 '16 at 19:39
  • I'm not sure I understand, could you show me in the fiddle? – jackspread124 Dec 08 '16 at 19:41
  • Why are you adding additional "+" divs? – Kevin B Dec 08 '16 at 19:42
  • You need to use a delegated event handler as you're appending new `.comment-add` elements to the DOM after it loads, see the duplicate question I marked for more information. Here's a working update: https://jsfiddle.net/RoryMcCrossan/DTcHh/27704/ – Rory McCrossan Dec 08 '16 at 19:45
  • Because when you click the "+" div, it will turn into an editable comment box, once something is typed in, a post request will be send, then a success will be returned and after that, a new "+" div needs to pop up incase the user wants to add an additional comment – jackspread124 Dec 08 '16 at 19:51

1 Answers1

-1

The reason is because the new "+" is being generated dynamically, but the listener is only making elements already created have the listener. A simple solution is to change your actual event listener to the body which doesn't change instead of the element and use a .on( 'click' ) function.

  $(document).ready(function(){
      $('body').on( 'click', ".comment-add", function(){
          var c = "<span class='glyphicon glyphicon-plus'></span>"
          var b = "<a class='comment-add'>"+c+"</a>"
          var a = "<div class='panel-footer'>"+b+"</div>"
          $(this).parent().after(a);
      });
  });