The following code changes a div
with the id #CommentLikeDisplay
which previously had been set to display:none
to display:block
when one clicks a "like" button (.LikeCommentLink
). There are multiple like buttons on the page, and the code works perfectly, except for when the elements CommentLikeDisplay
and LikeCommentLink
are added dynamically with JQuery (they are both added as part of the same dynamically added comment, which isn't relevant). I don't understand, because even when the elements are dynamically added, the line $("#LikeCommentLink" myNumber).css("color", "#2078F4");
works perfectly, yet it can't make the div with display:none
appear. I checked in Google Developer Tools and the code does indeed change the element to display:block
when I click the button, but the div
still isn't appearing, and I have no idea why that is the case. As you can see, I have tried two different methods to change the div's style to display:block
, which does actually work in the code but not on the screen. However, as I said, the whole thing works when the elements are not dynamically added.
Thank you very much for your help!
$("#NewsfeedContainer").on('click', '.LikeCommentLink', function(event){ //comment or subcomment LIKE button clicked
let myID = $( this ).attr("id");
let myNumber = myID.substring(15);
$("#LikeCommentLink" myNumber).css("color", "#2078F4");
$('#CommentLikeDisplay' myNumber).addClass('CommentLikeDisplay_is_shown');
$("#CommentLikeDisplay" myNumber).css("display", "block");
});
The following is how I create the HTML, which is inserted via JQuery and works fine.
toInsert = "<span class = 'LikeCommentLink' data-wall_id = '" wall_id "' id = 'LikeCommentLink" response[0].new_post_id "' data-post_author_id = '" PostAuthorID "'>Like</span>";
toInsert =
"<div class = 'CommentLikeDisplay' id = 'CommentLikeDisplay" response[0].new_post_id "'>";
toInsert = "<img src = 'images/bluelike.png' />"
toInsert = "<div class = 'CommentLikeDisplayNumber' id = 'CommentLikeDisplayNumber" response[0].new_post_id "'>0</div>";
toInsert = "</div>";
CodePudding user response:
As you can see it works fine in this example with dynamic element.
let uniqueID = Math.random().toString(36).slice(2);
let likeComment = `<span id="like-${uniqueID}">Like Comment</span>`;
let likeCommentResponse = `<div id="CommentLikeDisplay${uniqueID}">Comment Liked</div>`;
$('#NewsfeedContainer').append(likeComment);
$('#NewsfeedContainer').append(likeCommentResponse);
$('#NewsfeedContainer').on('click','.LikeCommentLink', function() {
$('#CommentLikeDisplay' $(this).attr('id').substring(5)).addClass('CommentLikeDisplay_is_shown');
});
.CommentLikeDisplayNumber {
display: none;
}
.CommentLikeDisplay_is_shown {
display: block;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="NewsfeedContainer"></div>
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>