0

I am currently coding a comments system. Each comment has a reply icon next to it.

When that reply icon is clicked, I would like to add a div under the div whose reply icon was clicked.

Adding comments works fine:

<script>
    $("#submitComment").click(function() {
        var comment = $("#commentsInput").val();
        if ("<%= user.profilePic %>" == "undefined" || "<%= user.profilePic %>" == "null" || "<%= user.profilePic %>" == "") {
            $("#commentsBox").prepend("<div class='fullComment'><div class='userCommentBox'><div class='commentUsername'><%= user.username %></div><img class='userPic' src='../../../public/assets/miniProfilePic.png' /></div><div class='comment'>"+comment+"</div><img class='replyIcon' src='./../../public/assets/replyIcon.png'></div>");
        } else {
            $("#commentsBox").prepend("<div class='fullComment'><div class='userCommentBox'><div class='commentUsername'><%= user.username %></div><img class='userPic' src='https://storage.googleapis.com/gaminghub-upload/<%= user.profilePic %>' /></div><div class='comment'>"+comment+"</div><div><img class='cross' src='./../../public/assets/cross.png'><img class='replyIcon' src='./../../public/assets/replyIcon.png'></div></div>");                     
        }
    })

...but I don't know how to add a reply under the correct div:

    $(".replyIcon").click(function () {
        ("<div>dfksjflsakdjfé</div>").insertAfter($(this).parent());
    })
</script>

Nothing happens when I click on the reply icon. My goal is to make another text area input appear just underneath the corresponding comment and move it sideways a little so we can see the distinct thread that is being created by the reply.

How can I add a div underneath the one whose reply icon was clicked ?

Daniel Beck
  • 20,653
  • 5
  • 38
  • 53
TheProgrammer
  • 1,409
  • 4
  • 24
  • 53
  • 1
    I believe that the issue is that you're trying to attach an event listener to a non-existing element (at the time that the above script is running). Take a look at this: https://stackoverflow.com/questions/14258787/add-event-listener-on-elements-created-dynamically. – Catalyst Jun 10 '17 at 18:20

1 Answers1

1

The .replyIcon elements are added to the document after you try to bind click events to those elements, so nothing gets bound.

Instead, bind the event to an element that does exist, and delegate it to .replyIcon; this way the function you want will be called even on newly-added .replyIcon elements:

$("document").on("click", ".replyIcon", function () {
    $("<div>dfksjflsakdjfé</div>").insertAfter($(this).parent());
});

(It would be better to choose a more specific location than "document" to hang the event on, though, as this ends up running a bit of code every time the user clicks anywhere. Limit the overspill by choosing the deepest DOM node that is certain to contain all the reply buttons.)

Daniel Beck
  • 20,653
  • 5
  • 38
  • 53