I'm using JavaScript to create an anchor tag for a popover. The code works perfectly. But then I need to get the anchor tag's id in a different function, but it's not working for some reason. I'm just learning JavaScript / JQuery so I think it may be some fundamental scope issue I don't know yet.
The code where I create the anchor tag:
$(document).ready(function(){
$('.image-options').each(function() {
var icon_id = $(this).attr('id');
a_tag_id = icon_id + "a";
var popString1 = "";
popString1 = popString1 + "<a href=“” class='options collect-modal' id='" + a_tag_id + "'>Add to collection <span class='icon-pop'><i class='fa-solid fa-plus'></i></span></a>";
$(icon_id).attr('data-bs-title', popString1);
});
});
This is the other code:
$(document).ready(function() {
$(".collect-modal").click(function(e) {
e.preventDefault();
var buttonId = $(this).attr('id');
alert(buttonId);
});
});
Please let me know if any additional info/code is needed.
EDIT: As suggested, I suspect it's an issue of direct vs delegated event handlers. Also, as requested I'm sharing an MRE:
$(document).ready(function(){
$('.image-options').each(function() {
var icon_id = $(this).attr('id');
a_tag_id = icon_id + "a";
var popString1 = "";
popString1 = popString1 + "<a href=“” class='options collect-modal' id='" + a_tag_id + "'>Add to collection <span class='icon-pop'><i class='fa-solid fa-plus'></i></span></a>";
$(icon_id).attr('data-bs-title', popString1);
});
});
$(document).click(".collect-modal", function(e) {
e.preventDefault();
var buttonId = $(this).attr('id');
alert(buttonId);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<div class="card border-0 overflow-hidden">
<div class="position-relative">
<img class="card-img-top card-img-bottom" data-bs-toggle="modal" data-bs-target="#myModal" src="https://picsum.photos/200" id="125img">
</div>
<a class="btn-opt btn-sm image-options" data-bs-container="body"
data-bs-toggle="popover" data-bs-placement="left" data-bs-html="true" id="125i"><i class="fa-solid fa-ellipsis"></i></a>
</div>
I changed the second code as suggested by @disinfor and at least it does something now, but now I get an undefined error.