verlager
verlager

Reputation: 876

event listener to close current dialog

The below code only works for the first dialog (BOB JONES) and the second dialog (ROBERT ABREAU) will open but not close onclick outside the dialog. I will have 150 more dialogs of text associated with student photos of a chess grandmaster. So IDK if I can use an event listener as per closeDialog() to close the current open dialog. Maybe a solution would involve getElementsByClassName. And I could patch that into the js code below, and omit the "onclick = "closeDialog();" on each dialog.

What's a good plan?

html

<!-- BOB JONES -->
<dialog id = "B-JONES" onclick = "closeDialog('B-JONES');">
<div class="test">
<p>Blah blah blah</p>
</div>
</dialog>
<!-- END BOB JONES

<!-- ROBERT ABREAU -->
<dialog id = "R-ABREAU" onclick = "closeDialog('R-ABREAU');">
<div class="test">
<p>Blah blah blah</p>
</div>
</dialog>
<!-- END ROBERT ABREAU -->

... 150 more

JS

function closeDialog(dialogID) {
 document.querySelector('dialog').addEventListener('click', function(e) {
if(!e.target.closest('div')) { e.target.close();}
 });
}

Upvotes: 0

Views: 616

Answers (1)

tomerpacific
tomerpacific

Reputation: 6475

Per your comment, the code you are looking for can be somewhere along these lines:

<!-- BOB JONES -->
<dialog id = "B-JONES" onclick = "closeDialog('B-JONES');">
<div class="test">
<p>Blah blah blah</p>
</div>
</dialog>
<!-- END BOB JONES

<!-- ROBERT ABREAU -->
<dialog id = "R-ABREAU" onclick = "closeDialog('R-ABREAU');">
<div class="test">
<p>Blah blah blah</p>
</div>
</dialog>
<!-- END ROBERT ABREAU -->

JS

 function closeDialog(dialogID) {
 let dialog = document.getElementById(dialogId);
 if (dialog) {
      dialog.close();
 }
}

Just make sure that the IDs of your dialogs are unique.

Upvotes: 1

Related Questions