You Can Schedule Modal Popups using Javascript

jack.from.canada
140 Posts
jack.from.canada posted this 17 November 2024
Ask a Question

I use modal popups to make announcements on standard HTML sites created with Nicepage. When I use Nicepage to create WordPress themes, there are plugins that can be used to "schedule" when a popup can be active, and when it should be deactivated (i.e. after an event has been completed). But for a standard HTML website, Nicepage has no such native functionality.

Experimenting with AI, I was able to create a Javascript solution that will allow Nicepage projects to define popups which will not only be displayed on the specified pages and after a specified delay; but will also allow them to be automatically activated and deactivated based on a required start/end schedule.

If you need this functionality now, this guide should give you some direction on how to implement it yourself. Nicepage already supports giving a custom ID to the Modal Popup (usually a self-generated ID beginning with "carousel_", but it can be user-specified).

In the code below, you will see a reference to startTime, endTime and the string myModalId (where myModalId would be replaced by your popup's actual modal popup ID).

The Javascript code below should be added to an HTML element within your project.

===================================

<script>

document.addEventListener('DOMContentLoaded', (event) => {

// Define the start and end times for the modal popup
const startTime = new Date('2024-11-18T00:00:00'); // example Start time
const endTime = new Date('2024-11-19T00:00:00'); // example End time
let initialCheckDone = false;

// Function to check if the current time is within the defined period
function isWithinSchedule() {

const now = new Date();
return now >= startTime && now <= endTime;

}

// Function to show or hide the modal based on the schedule
function toggleModal(initialCheck = false) {

const modal = document.getElementById('myModalId');
if (modal) {
    if (isWithinSchedule()) {
        if (initialCheck || (!initialCheck && modal.style.display === 'none')) {
            modal.style.display = 'block';
        }
    } else {
        modal.style.display = 'none';
    }
} else {
    console.error('Modal element with ID "myModalId" not found');
}

}

// Function to handle the close button
function closeModal() {

const modal = document.getElementById('myModalId');
if (modal) {
    modal.style.display = 'none';
}

}

// Add event listener to the close button
const closeButton = document.querySelector('#myModalId .u-dialog-close-button');
if (closeButton) {

closeButton.addEventListener('click', closeModal);

} else {

console.error('Close button not found within the modal');

}

// Call the function to set the initial state of the modal
toggleModal(true);
initialCheckDone = true;

// Optional: Update the modal state every minute without changing it if already closed
setInterval(() => {

if (!initialCheckDone) {
    toggleModal(false);
}

}, 60000);

});

(end-script tag)

===================================

Please feel free to use this method for a quick way to implement scheduled modal popups.

Last edited 17 November 2024 by jack.from.canada

Vote to pay developers attention to this features or issue.
2 Replies
Order By: Standard | Newest
jack.from.canada
140 Posts
jack.from.canada posted this 29 January 2025

The code above was working fine during the period when the modal was intended to be active. But, when the expiration time came, I found that the code was actually blocking the proper scrolling of the webpage. It was almost as if the popup was still appearing, but there was no way to close it (because the popup was not being displayed).

After some work, I have found a solution that appears to work. So, here is the REVISED code for scheduling modal popups in Nicepage.

(begin-script tag)
document.addEventListener('DOMContentLoaded', (event) => {

const elementId = 'myModalId'; // Change this to your modal element ID

// Define the start and end times for the modal popup
const startTime = new Date('2024-12-16T02:45:00'); // example Start time
const endTime = new Date('2025-01-01T21:01:00'); // example End time

// Function to check if the current time is within the defined period
function isWithinSchedule() {
    const now = new Date();
    return now >= startTime && now <= endTime;
}

// Function to clean up any event listeners or intervals
function cleanup() {
    const closeButton = document.querySelector(`#${elementId} .u-dialog-close-button`);
    if (closeButton) {
        closeButton.removeEventListener('click', closeModal);
    }
    clearInterval(toggleInterval);


    // Remove modal and overlay from the document
    const modal = document.getElementById(elementId);
    if (modal) {
        modal.parentNode.removeChild(modal);
    }
    const overlay = document.querySelector('.u-dialog-block');
    if (overlay) {
        overlay.parentNode.removeChild(overlay);
    }
}

// Variable to hold the interval reference
let toggleInterval;

// Function to show or hide the modal based on the schedule
function manageModal() {
    const modal = document.getElementById(elementId);
    if (modal) {
        if (isWithinSchedule()) {
            // Allow the original program to handle modal display
        } else {
            modal.style.display = 'none';
        }
    }
}

// Function to handle the close button
function closeModal() {
    const modal = document.getElementById(elementId);
    if (modal) {
        modal.style.display = 'none';
    }
}

// Function to detect when the modal is displayed on screen
function observeModal() {
    const modal = document.getElementById(elementId);
    if (modal) {
        const observer = new MutationObserver(mutations => {
            mutations.forEach(mutation => {
                if (mutation.attributeName === 'style' && modal.style.display === 'block') {
                    // Modal appeared on screen
                }
            });
        });
        observer.observe(modal, { attributes: true });
    }
}

// Initial check for schedule and modal element
if (isWithinSchedule()) {
    const modal = document.getElementById(elementId);
    if (modal) {
        // Add event listener to the close button
        const closeButton = document.querySelector(`#${elementId} .u-dialog-close-button`);
        if (closeButton) {
            closeButton.addEventListener('click', closeModal);
        }

        // Call the function to manage the modal state
        manageModal();

        // Observe the modal to detect when it appears
        observeModal();

        // Update the modal state every minute and close it if the end time is reached
        toggleInterval = setInterval(() => {
            if (!isWithinSchedule()) {
                closeModal();
                cleanup(); // Ensure cleanup is called after closing the modal
            } else {
                observeModal(); // Re-observe the modal appearance
            }
        }, 60000);
    } else {
        cleanup();
    }
} else {
    cleanup();
}

});
(end-script tag)

Last edited 29 January 2025 by jack.from.canada

Support Team
Support Team posted this 29 January 2025

Hi Jack,

Thanks for sharing. I hope it could help other users.

...................................................
Sincerely,
Hella
Nicepage Support Team

Please subscribe to our YouTube channel: http://youtube.com/nicepage?sub_confirmation=1
Follow us on Facebook: http://facebook.com/nicepageapp

You must log in or register to leave comments