Set a jQuery cookie to show popup only once

后端 未结 6 538
野性不改
野性不改 2020-12-14 02:36

I\'m an absolute newbie in jQuery. I\'m learning, but there is a Christmas message that I need to get up and running within no time.

I\'ve included these in the head

相关标签:
6条回答
  • 2020-12-14 03:14

    Using js-cookie https://github.com/js-cookie/js-cookie

    And Magnific Popup http://dimsemenov.com/plugins/magnific-popup/

    And inspired by the other answers I did this which I'm posting as it took me ages to work out so may help someone else. If anyone wants to edit and improve my code feel free.

     <script type="text/javascript">
    function setCookie() {
        Cookies.set('test_status', '1', { expires: 1 })
        return false;
    }
    </script>
    
    <script type="text/javascript">//<![CDATA[
    $(document).ready(function(){
       if (Cookies.get('test_status') != '1') {
             setTimeout(function(){
        $.magnificPopup.open({
         items: {
                src: '#message_popup' //ID OF INLINE ELEMENT
                    },
                type:'inline',
          mainClass: 'mfp-zoom-out',
           closeBtnInside: true,
            fixedContentPos: true,
            removalDelay: 500,
                });
         }, 3000);  // equals 50 seconds
        Cookies.set('test_status', '1', { expires: 1}); }
       });
      //]]>
    </script>
    
    <script type="text/javascript">
      function closePopup() {
      $.magnificPopup.close();
    }
    </script>
    
    //MY POP UP
    <div id="message_popup" class="white-popup mfp-hide typography">
    <button title="CLOSE" type="button" onClick="closePopup();">x</button>
      <div id="pop_inner">
       HELLO WORLD
      </div>
    </div>
    
    0 讨论(0)
  • 2020-12-14 03:17

    I had the same problem and I found this solution:

    $(document).ready(function () {
        var cookie = document.cookie;
        if (cookie == "") {
            //show popup depending on url
            var url = window.location;
            if (url != "http://localhost/test/jquery-popup.html") {                                    
                setTimeout(function () {
                    $.fn.colorbox({ html: '<div style="width:301px;height:194px;"><a href="http://livebook.in/"><img src="res/homer.jpg" style="width:301px;height:194px;" alt="The linked image" /></a></div>', open: true });
                }, 500);   
            }else {
                setTimeout(function () {
                    $.fn.colorbox({html:'...', open:true});
                }, 500);
            }
    
            //set timeout for closing the popup
            setTimeout(function () { $.fn.colorbox.close(); }, 3000);
    
            //set cookie
            var d = new Date();
            d.setTime(d.getTime() + (30 * 24 * 60 * 60 * 1000)); //expire in 30 days
            var expires = "expires=" + d.toGMTString();
            document.cookie = "apparsoYES" + "=" + "YES" + "; " + expires;    
        }
    });
    

    this script creates a popup on page load, auto close it, creates a cookie so the popoup is showed only once time and can show different popups depending on the page

    0 讨论(0)
  • 2020-12-14 03:19

    I guess what you are looking for is, when a new user visits your Webpage, you show a pop up, but as he surfs through other pages, the pop window should not come up.

    Its very easy to achieve through cookies, check this code sample, this will help you

    So i am including the code snippet used(you can also follow the below link for the same)

    So, the script part is

    var expDays = 1; // number of days the cookie should last
    
    var page = "only-popup-once.html";
    var windowprops = "width=300,height=200,location=no,toolbar=no,menubar=no,scrollbars=no,resizable=yes";
    
    function GetCookie (name) {
    var arg = name + "=";
    var alen = arg.length;
    var clen = document.cookie.length;
    var i = 0;
    while (i < clen) {
    var j = i + alen;
    if (document.cookie.substring(i, j) == arg)
    return getCookieVal (j);
    i = document.cookie.indexOf(" ", i) + 1;
    if (i == 0) break;
    }
    return null;
    }
    function SetCookie (name, value) {
    var argv = SetCookie.arguments;
    var argc = SetCookie.arguments.length;
    var expires = (argc > 2) ? argv[2] : null;
    var path = (argc > 3) ? argv[3] : null;
    var domain = (argc > 4) ? argv[4] : null;
    var secure = (argc > 5) ? argv[5] : false;
    document.cookie = name + "=" + escape (value) +
    ((expires == null) ? "" : ("; expires=" + expires.toGMTString())) +
    ((path == null) ? "" : ("; path=" + path)) +
    ((domain == null) ? "" : ("; domain=" + domain)) +
    ((secure == true) ? "; secure" : "");
    }
    function DeleteCookie (name) {
    var exp = new Date();
    exp.setTime (exp.getTime() - 1);
    var cval = GetCookie (name);
    document.cookie = name + "=" + cval + "; expires=" + exp.toGMTString();
    }
    var exp = new Date();
    exp.setTime(exp.getTime() + (expDays*24*60*60*1000));
    function amt(){
    var count = GetCookie('count')
    if(count == null) {
    SetCookie('count','1')
    return 1
    }
    else {
    var newcount = parseInt(count) + 1;
    DeleteCookie('count')
    SetCookie('count',newcount,exp)
    return count
       }
    }
    function getCookieVal(offset) {
    var endstr = document.cookie.indexOf (";", offset);
    if (endstr == -1)
    endstr = document.cookie.length;
    return unescape(document.cookie.substring(offset, endstr));
    }
    
    function checkCount() {
    var count = GetCookie('count');
    if (count == null) {
    count=1;
    SetCookie('count', count, exp);
    
    window.open(page, "", windowprops);
    
    }
    else {
    count++;
    SetCookie('count', count, exp);
       }
    }
    

    And following will be the body of DOM,

    <BODY OnLoad="checkCount()">
    

    http://www.jsmadeeasy.com/javascripts/Cookies/Only%20Popup%20Once/index.htm

    0 讨论(0)
  • 2020-12-14 03:27

    First include the jquery library.

    After include the below script for cookies in jquery.

    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-cookie/1.4.1/jquery.cookie.min.js"></script>
    

    Now put the below code into the footer :

    $(document).ready(function() {
           // initially popup is hidden:
            $('#stay-in-toch.popup-outer').hide();
            // Check for the "whenToShowDialog" cookie, if not found then show the dialog and save the cookie.
            // The cookie will expire and every 2 days and the dialog will show again.
            if ($.cookie('whenToShowDialog') == null) {
                // Create expiring cookie, 2 days from now:
                $.cookie('whenToShowDialog', 'yes', { expires: 2, path: '/' });
    
                // Show dialog
                 $('#stay-in-toch.popup-outer').show();       
            }
        });
    
    0 讨论(0)
  • 2020-12-14 03:28

    Something of this kind might be of help:

    $(document).ready(function(){
       if ($.cookie('test_status') != '1') {
        //show popup here
        $.cookie('test_status', '1', { expires: 60}); }
       });
    
    0 讨论(0)
  • 2020-12-14 03:32

    You can try this

    $(document).ready(function() {  
        if ($.cookie('test_status')) {
            return;
        }
    
        //Rest of your code here
    });
    
    0 讨论(0)
提交回复
热议问题