popup open only 1 time after being closed, even after reloading page

Asked

Viewed 8,606 times

5

I wonder how to create one of those popup that usually appear in large portals (not in flash), but with div and javascript pure, which after being closed, the script detect this and it will no longer open, even after reloading the page or navigating between internal pages.

4 answers

7


You will need to control if the popup display has already been made for a given user, and for that there are some ways:

To display the popup you can use a ready-made library:

Store in the client:

Store the information on the client side, using some of the browser’s Storage forms: cookie, localstorage, sessionstorage.

  • cookie: stores the information in the form of cookie, which has a specific date to expire, in this case after that date, the cookie would be displayed again, obviously it is possible to set a very distant date in a way that seems to be forever. Unfortunately, javascript does not have a cute function to do this, however it is the way that will work with the most browsers. If you are using jQuery, you can use the plugin jquery.cookies:

    // verificando se o cookie está setado, caso contrário exibe o popup
    if (!$.cookie("popup-exibida"))
    {
         // exibir popup usando a sua lib de popup preferida
    }
    

    Code of the popup (using jQuery UI Dialog):

    $(function() {
        $( "#dialog-modal" ).dialog({
            height: 140,
            close: function( event, ui ) {
                var date = new Date();
                var minutes = 30;
                date.setTime(date.getTime() + (minutes * 60 * 1000));
                $.cookie("popup-exibida", "1", { expires: date }); // expira em 30 minutos
            }
        });
    });
    
  • sessionstorage: stores the information in the user’s browsing session, which is discarded by the browser when it is closed, so the information is lost when closing the browser. This feature is much easier to use than cookies, but it is a newer feature, and requires a more modern browser:

    // verificando se o storage possui a variável setada, caso contrário exibe o popup
    if (!window.sessionStorage.getItem("popup-exibida"))
    {
         // exibir popup usando a sua lib de popup preferida
    }
    

    Setting variable in Session-Storage

     // setar cookie para impedir uma nova exibição
     window.sessionStorage.setItem("popup-exibida", "1");
    
  • localstorage: stores the information permanently on the user’s computer, and if it changes from computer the popup would be displayed again. This feature is similar to sessionStorage in terms of practicality, and is also a recent feature, so compatibility is restricted to more modern browsers:

    // verificando se o storage possui a variável setada, caso contrário exibe o popup
    if (!window.localStorage.getItem("popup-exibida"))
    {
         // exibir popup usando a sua lib de popup preferida
    }
    

    Setting the variable at the location-Storage

     // setar cookie para impedir uma nova exibição
     window.localStorage.setItem("popup-exibida", "1");
    

Store on the server:

Store the information on the server side, using user navigation session or a database, or whichever one you prefer. In javascript you would have to make an ajax call when the popup was closed, indicating to the server that the popup should no longer be rendered in output.

  • browsing session: Store in the user’s browsing session on the server, and when the information expires it is lost. The web programming technologies I know all provide a browsing session, which allows you to store the information.

  • database: If you are a user logged in to the system, you could store this information in a database on the server, so the information would be persistent for all the existence of that user.

4

Here a solution without jQuery. Example of functions for Cookie of this reply in Soen and the Domready this other also in Soen. The CSS is from Modal Reveal plugin, but used only for testing and removed all jQuery from the plugin in this example:

<!DOCTYPE html>
    <head>
        <meta charset="utf-8" />
        <title>Popup Demo</title>

        <style type="text/css">
            /* From http://zurb.com/playground/reveal-modal-plugin */
            body { 
                font-family: "HelveticaNeue","Helvetica-Neue", "Helvetica", "Arial", sans-serif; 
                }
            .texto {
                display:block; 
                margin-top: 100px; 
                text-align: center; 
                font-size: 70px; 
                color: #06f; 
                }
            .reveal-modal-bg { 
                position: fixed; 
                height: 100%;
                width: 100%;
                background: #000;
                background: rgba(0,0,0,.8);
                z-index: 100;
                display: none;
                top: 0;
                left: 0; 
                }

            .reveal-modal {
                visibility: hidden;
                top: 100px; 
                left: 50%;
                margin-left: -300px;
                width: 520px;
                position: absolute;
                z-index: 101;
                padding: 30px 40px 34px;
                }


            .reveal-modal .close-reveal-modal {
                font-size: 22px;
                line-height: .5;
                position: absolute;
                top: 8px;
                right: 11px;
                color: #aaa;
                text-shadow: 0 -1px 1px rbga(0,0,0,.6);
                font-weight: bold;
                cursor: pointer;
                }
        </style>
    </head>
    <body>

        <p class="texto">Conteúdo normal da página</p>

        <div id="myModal" class="reveal-modal">
            <h1>Exemplo de popup modal</h1>
            <p>Ipsum lorem ipsum.</p>
            <a class="close-reveal-modal">&#215;</a>
        </div>

        <script type="text/javascript">
        /* From https://stackoverflow.com/a/20604307/1287812 */
        function setCookie( name, value, exp_y, exp_m, exp_d ) 
        {
            var cookie_string = name + "=" + escape(value);
            var expires = new Date(exp_y, exp_m, exp_d);
            cookie_string += "; expires=" + expires.toGMTString();
            document.cookie = cookie_string;
        }

        /* From https://stackoverflow.com/a/20604307/1287812 */
        function getCookie( cookie_name) 
        {
            var results = document.cookie.match('(^|;) ?' + cookie_name + '=([^;]*)(;|$)');
            return results ? unescape(results[2]) : null;
        }

        /* From https://stackoverflow.com/a/16196548/1287812 */
        var execute = function () 
        {
            if( !getCookie('popup') ) 
            {
                document.getElementById('myModal').style.visibility = 'visible';
                setCookie('popup', 'visto', 2014, 4, 12);
            }
            else
                console.log('cookie já definido');

        };

        /* From https://stackoverflow.com/a/16196548/1287812 */
        if ( !!(window.addEventListener) )
            window.addEventListener("DOMContentLoaded", execute)
        else // MSIE
            window.attachEvent("onload", execute)

        </script>

    </body>
</html>

1

Usually you apply a Fancybox with the banner and arrow a Cookie in the browser. Then check: IF this Cookie still exists it no longer displays the Popup. After it expires (you set the number of days/hours/minutes/etc) or when you clear the cookies, it appears again.

  • 4

    Set an example for the boy ! :)

  • 1

    I imagined something with cookies even. but then, I remembered that cookies is not yet my thing.

1

Example made with jQuery Cookie

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Exemplo</title>
<script type="text/javascript"  src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script type="text/javascript"  src="//cdnjs.cloudflare.com/ajax/libs/jquery-cookie/1.3.1/jquery.cookie.min.js"></script>
<script src="jquery.modal.js" type="text/javascript" charset="utf-8"></script>
<link href="jquery.modal.css" rel="stylesheet" type="text/css">
<script type="text/javascript">
    $(function() {
        /*Confere se sts já existe na Cookie*/
        if ($.cookie('sts') != '1')
        {
            setTimeout(function()
            {        
            $("#data").modal(); /*Executa o Modal*/       
                /*Gerando os dados do Cookie*/
                var date = new Date(); 
                var tempo = 30; // minutos 
                date.setTime(date.getTime() + (tempo * 60 * 1000));
                jQuery.cookie('sts', '1', { expires: date });
            }, 1000);
        }

    });     
    </script>

</head>
<body>
<!--https://github.com/kylefox/jquery-modal-->
<div style="display:none" id="data" class="modal">
    Lorem ipsum dolor sit amet, consectetur adipiscing elit.
    Lorem ipsum dolor sit amet, consectetur adipiscing elit.
    Lorem ipsum dolor sit amet, consectetur adipiscing elit.
    Lorem ipsum dolor sit amet, consectetur adipiscing elit.
    Lorem ipsum dolor sit amet, consectetur adipiscing elit.
    Lorem ipsum dolor sit amet, consectetur adipiscing elit.
    Lorem ipsum dolor sit amet, consectetur adipiscing elit.
    Lorem ipsum dolor sit amet, consectetur adipiscing elit.
</div>
</body>
</html>

Client Storage, prevents access to the server and makes a better control of a simple modal, having no Jquery Cookie a simple routine with expiration setting of 30 minutes

References:

Browser other questions tagged

You are not signed in. Login or sign up in order to post.