Close modal

This commit is contained in:
andrea 2024-09-26 11:52:24 +02:00
parent 1aeaed646e
commit 4c5aed1367
3 changed files with 46 additions and 21 deletions

View file

@ -22,3 +22,4 @@
grid-template-columns: 20% 20% 20% 20% 20%;
}
}

View file

@ -1 +0,0 @@
andrea@lv5.321700:1727085997

View file

@ -11,6 +11,7 @@ class GridOfPhotos extends HTMLElement {
// LIsten for events
this.addEventListener('click', this);
this.addEventListener('keydown', this);
}
/**
@ -18,6 +19,9 @@ class GridOfPhotos extends HTMLElement {
*/
async connectedCallback () {
// Create the dialog element
this.dialog = document.createElement('dialog');
// Fetch the photos from the API
this.photos = await this.fetchPhotos();
@ -29,7 +33,7 @@ class GridOfPhotos extends HTMLElement {
// Render the element
this.innerHTML = `
<div>
${this.photos.map( (image) => { return `<img src="${image.url}" alt="${image.description}"></img>` } ).join('')}
${this.photos.map( (image) => { return `<img id="${image.id}" src="${image.url}" alt="${image.description}"></img>` } ).join('')}
</div>
`
}
@ -58,30 +62,26 @@ class GridOfPhotos extends HTMLElement {
* @param {Event} event - The event object
*/
handleEvent (event) {
console.log(event);
this[`on${event.type}`](event);
}
/**
* Handle the click event
* @param {Event} event - The event object
* Open the modal window that shows the photo.
*/
onclick (event) {
handleOpenPhoto (event) {
if (!event.target.closest('img')) return;
let dialog = document.createElement('dialog');
dialog.setAttribute('open', '');
let image = this.photos.find( (image) => { return image.id === event.target.getAttribute('id') } );
dialog.innerHTML = `
this.dialog.setAttribute('open', '');
this.dialog.innerHTML = `
<article>
<h2>Confirm Your Membership</h2>
<h2>${image.name}</h2>
<p>
Thank you for signing up for a membership!
Please review the membership details below:
${image.description}
</p>
<ul>
<li>Membership: Individual</li>
<li>Price: $10</li>
</ul>
<img id="${image.id}" src="${image.url}" alt="${image.description}"></img>
<footer>
<button class="secondary">
Close
@ -89,13 +89,38 @@ class GridOfPhotos extends HTMLElement {
</footer>
</article>
`
this.append(dialog);
this.append(this.dialog);
}
/**
* Close the modal window that shows the photo.
*/
handleClosePhoto (event) {
if (!event.target.closest('dialog button')) return;
this.dialog.close();
this.dialog.remove();
}
/**
* Handle the click event
* @param {Event} event - The event object
*/
onclick (event) {
this.handleOpenPhoto(event);
this.handleClosePhoto(event);
}
onkeydown (event) {
console.log(event);
if (event.key === "Escape") {
this.handleClosePhoto(event);
}
}
}
// Define the new web component
if ('customElements' in window) {
customElements.define('grid-of-photos', GridOfPhotos);
customElements.define('grid-of-photos', GridOfPhotos);
}