78 lines
2.1 KiB
JavaScript

/**
* Modal utilities for handling dynamic content loading
*/
class ModalHandler {
constructor(modalId, contentElementId) {
this.modalElement = document.getElementById(modalId);
this.contentElement = document.getElementById(contentElementId);
this.modal = null;
if (this.modalElement && typeof bootstrap !== "undefined") {
this.modal = new bootstrap.Modal(this.modalElement);
}
}
/**
* Load content into modal via AJAX and show it
* @param {string} url - URL to fetch content from
* @param {string} errorMessage - Message to show on error
*/
async loadAndShow(url, errorMessage = "Error loading content.") {
if (!this.modal || !this.contentElement) {
console.error("Modal or content element not found");
return;
}
try {
const response = await fetch(url);
const html = await response.text();
this.contentElement.innerHTML = html;
this.modal.show();
} catch (error) {
console.error("Error loading modal content:", error);
this.contentElement.innerHTML = `<div class="modal-body text-danger">${errorMessage}</div>`;
this.modal.show();
}
}
/**
* Set up click handlers for elements that should open the modal
* @param {string} selector - CSS selector for clickable elements
* @param {string} urlAttribute - Attribute name containing the URL (default: 'data-url')
*/
setupClickHandlers(selector, urlAttribute = "data-url") {
document.addEventListener("DOMContentLoaded", () => {
document.querySelectorAll(selector).forEach((element) => {
element.addEventListener("click", (e) => {
e.preventDefault();
const url = element.getAttribute(urlAttribute);
if (url) {
this.loadAndShow(url);
}
});
});
});
}
/**
* Show the modal with custom content
* @param {string} content - HTML content to display
*/
showWithContent(content) {
if (!this.modal || !this.contentElement) return;
this.contentElement.innerHTML = content;
this.modal.show();
}
/**
* Hide the modal
*/
hide() {
if (this.modal) {
this.modal.hide();
}
}
}