I am creating a web app that connects to a news API and shows articles. For each article, I have created a card and a modal in handlebars.
Upon clicking the button on each respective card, I would like a modal to open with its unique information.
I am trying to add an event listener for the button on the card to open the modal.
<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>
{{@index}}
</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>
Clicking on the "Open Modal" button does nothing, nor does it give an error.
I am unsure if the button class {{@index}} is being read properly by the script.
Any assistance or tips would be greatly appreciated!