I've been working on developing a web application that interacts with a news API to display articles. Each article is presented in a card format, and I have also incorporated modals using handlebars.
My goal is for each card's button to trigger the opening of a modal containing unique information related to that specific article.
I'm currently facing an issue where clicking the button on the card does not open the corresponding modal, nor does it generate any error messages.
I suspect that there might be an issue with how the script is interpreting the button's class, denoted as {{@index}}.
<div class="">
{{!-- #each article --}}
<div class="row">
{{#each articles}}
<div class="col-12-sm col-6-md col-3-lg">
<div class="card m-2">
<div class="card-body">
<h5 class="card-title">{{title}}</h5>
<p class="card-text">{{description}}</p>
</div>
<img class="card-image" src="{{urlToImage}}" alt="Card image cap">
<button id="mybtn" class="{{@index}}">Open Modal</button>
</div>
</div>
{{/each}}
</div>
</div>
{{#each articles}}
<!-- The Modal -->
<div id="modid" class="modal">
<!-- Modal content -->
<div class="modal-content">
<span class="close">×</span>
<p>Some text in the Modal..</p>
</div>
</div>
{{/each}}
<script>
let modal = document.getElementById("modid");
let btn = document.getElementById("mybtn");
let span = document.getElementsByClassName("close")[0];
btn.onclick = function() {
modal.style.display = "block";
}
span.onclick = function() {
modal.style.display = "none";
}
window.onclick = function(event) {
if (event.target == modal) {
modal.style.display = "none";
}
}
const btn = document.querySelector('.{{@index}}');
btn.addEventListener('click', function(event){
console.log('Button Clicked');
}
</script>
If you have any insights or advice on how to resolve this issue, I would greatly appreciate your input!