popup open only once after being closed, even after reloading page

5

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

    
asked by anonymous 11.04.2014 / 15:28

4 answers

7

You will need to control whether the popup display has already been made for a given user, and for this there are a few ways:

To display the popup you can use a library already ready:

Store on client:

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

  • cookie: stores information in the form of a 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 date far form that seems to be forever. Unfortunately, javascript does not have a cute function to do this, however it is the way it will work with the largest amount of browsers. If you're using jQuery, you can use the jquery.cookies plugin :

    // 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
    }
    

    Popup code (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 the browser is closed. 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 the 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 he changes his computer the popup would be displayed again. This feature is similar to sessionStorage in terms of convenience, 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 in local-storage

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

Store on server:

Store the information on the server side, using a user's browsing session or a database, or whatever you prefer. In javascript I would have to make an ajax call when the popup was closed, telling the server that the popup should no longer be rendered in the output.

  • browsing session: Store in the browsing session of the user on the server, and when it expires the information 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 logged-in user, you could store this information in a database on the server, so information would be persistent for all that user's existence. / p>
11.04.2014 / 15:44
4

Here is a solution without jQuery. The sample cookie functions this answer in SOen and DOMReady of this other one also in SOen . The CSS is from the Reveal Modal plugin , but I just used it for testing and removed all the jQuery from the plugin in this example: / p>

<!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>
    
11.04.2014 / 18:08
1

Generally, you apply a Fancybox with the banner and a Cookie arrow in the browser. Then check: If this Cookie still exists, it will no longer display Popup. After it expires (you hit the number of days / hours / minutes / etc) or when you clear cookies, it reappears.

    
11.04.2014 / 15:35
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, avoids server access, and makes better control of a simple modal, having Jquery Cookie a simple routine with

11.04.2014 / 16:42