Home > database >  I need a cookie or localstorage solution
I need a cookie or localstorage solution

Time:07-25

I'd like this window.onload to only trigger the modal once a month but I am having trouble making it work - please help

<script type="text/javascript">
    window.onload = function () {
        OpenBootstrapPopup();
    };
    function OpenBootstrapPopup() {
    $("#simpleModal").modal('show');

    }
    function myFunctionClose() {
        $("#simpleModal").modal('hide');
    }        
</script>

CodePudding user response:

Its actually quite simple. You can save in local storage the last time the popup showed up. But be aware of some details: local storage only saves text, so to save a date you can save the timestamp.

It would look something like this:

<script type="text/javascript">
    window.onload = function () {
        OpenBootstrapPopupIfOneMonthHasPassed();
    };
    
    function OpenBootstrapPopupIfOneMonthHasPassed() {   
        let lastTimeModalWasOpened = localStorage.getItem("lastTimeModalOpened");
        // if has never opened, then open it 
        if (!lastTimeModalWasOpened) {
            return openModal();
        }
        // we need to convert it back to date object
        let dateObjectlastTimeModalWasOpened = new Date(parseInt(lastTimeModalWasOpened));
        // we substract the dates and get their difference in miliseconds. If you want to check if the month has changed instead of a fixed amount of days, you could compare the Date.month property or something else
        let timePassedSinceModalWasOpened = new Date() - dateObjectlastTimeModalWasOpened;
        // the difference is given in miliseconds, thus we need to divide in milisecons, seconds, minutes, hours, days
        if (timePassedSinceModalWasOpened / (1000 * 60 * 60 * 24 * 30) > 30) {
            return openModal();
        }
    }

    function openModal() {
        $("#simpleModal").modal('show');
        localStorage.setItem("lastTimeModalOpened", Date.now());
    }

</script>
  • Related