1

hello this is my first time asking a question on here, hope im not asking for too much, i created a lightbox type pop up that starts after 20 seconds, for my site, but i dont want the popup to keep reappearing if i continue browsing(session cookie), i have tried creating cookies but it seems that i am not doing it correctly. if you can help i would appreciate it very much thank you.

window.setTimeout(function () {

    $('.popupbox').ready(function () {
        $('.backdrop, .box').animate({
            'opacity': '.50'
        }, 300, 'linear');
        $('.box').animate({
            'opacity': '1.00'
        }, 300, 'linear');
        $('.backdrop, .box').css('display', 'block');
    });

    $('.close').click(function () {
        close_pop();
    });

    $('.backdrop').click(function () {
        close_pop();
    });
}, 20000);


if (!readCookie('hide')) {
    $('.popupbox').show();
}

function close_pop() {
    $('.backdrop, .box').animate({
        'opacity': '0'
    }, 300, 'linear', function () {
        $('.backdrop, .box').css('display', 'none');
    });

    $.cookie('hide', true, 1, {
        path: '/'
    });
    return false;
}
abc123
  • 17,855
  • 7
  • 52
  • 82
MysteryWhy
  • 13
  • 1
  • 4
  • 4
    possible duplicate of [How to set/unset cookie with jQuery?](http://stackoverflow.com/questions/1458724/how-to-set-unset-cookie-with-jquery), if you need more help that the attach let me know and i'll write the solution for you in a jsFiddle. It will be the same as the previously linked. – abc123 Aug 08 '13 at 05:41
  • @abc123 thank you for the response, i have never used cookies before, so i read that, is it that im not creating the cookie correctly or that i am not making the correct function to run it? or both. – MysteryWhy Aug 08 '13 at 22:18
  • Should be able to just include the library mentioned in that post then I believe your code looks fine. I can make a jsFiddle if needed. – abc123 Aug 09 '13 at 02:13
  • @abc123 i did use the library for the jquery cookies but it seems to not have worked, i would appreciate it if you could help me with a jsFiddle if you dont mind. thank you. – MysteryWhy Aug 10 '13 at 00:02
  • Answer added, let me know if you need anymore _help_. – abc123 Aug 10 '13 at 04:10
  • @abc123 my friend youre amazing! one last question, so in order for this code to work i must run it off a server right? cause im trying to run it internally and well the pop up still appears... – MysteryWhy Aug 12 '13 at 09:03
  • Nope, it is all client-side code. The below answer worked for me in Google Chrome. What browser are you using? I'd be happy to take a look at it in said browser. It might not work if you just save it as an HTML file, IE URL = `file:///C:/Users/[username]/Desktop/test.html` but if you setup a website in IIS it would work. – abc123 Aug 12 '13 at 14:34
  • @abc123 sorry its been like a week since i got back to you, its just that i tired entering the code into the website and it seems that that when i enter it the popup does not occur, i checked the debugger and it marks an error as "$.cookie is not a function. i dont mean to be a bother, but could you help me one more time. thank you! – MysteryWhy Aug 21 '13 at 02:13
  • @abc123 sorry its been like a week since i got back to you, its just that i tired entering the code into the website and it seems that that when i enter it the popup does not occur, i checked the debugger and it marks an error as "$.cookie is not a function, when i check the resources for cookies it marks that there are none. i dont mean to be a bother, but could you help me one more time. thank you! – MysteryWhy Aug 21 '13 at 02:48
  • you are missing the [jquery.cookie.js](https://github.com/carhartl/jquery-cookie) plugin make sure you include it. if it is included then make sure you do the following jQuery.cookie to see if it sees that. – abc123 Aug 21 '13 at 03:19
  • @abc123 i placed the plugin inside of the javascript, am i supposed to put inside of the html as well? – MysteryWhy Aug 21 '13 at 20:30
  • Yes, unless you did what i did in my jsFiddle you'll need to do a `script include` like you mentioned. :) – abc123 Aug 21 '13 at 20:42
  • @abc123 im sorry i keep annoying you but i keep try following your jsfiddle and i seem to have everything im supposed to but yet it seems to create everything but that darn cookie can i post my whole code and you look it over see if you catch something im missing? – MysteryWhy Aug 21 '13 at 21:50
  • Yes, feel free to post all your code. Also I rewrote this in basic JavaScript so you don't have to mess with jQuery if you don't want to. Let me know if you need more, thanks! – abc123 Aug 22 '13 at 02:21

1 Answers1

2

The below code will display a div after 20 seconds if the user clicks inside the div or on close the div will hide and won't show again unless they lose their cookies, even on reload.

Special Note: Unfortunately jquery.cookie.js plugin doesn't have a CDN so I inline included it below...please don't do this in production include it using normal script includes.

DEMO: jQuery jsFiddle

HTML

<div class="popupbox" style="display: none;">
    <div class="backdrop box"> 
        <span>Hello World I am a popup.</span>
        <input type="button" class="close" value="Close" />
    </div>
</div>

JS

$(function () {
    if (!$.cookie('hide')) {
        window.setTimeout(function () {
            $('.popupbox').show();
            $('.popupbox').ready(function () {
                $('.backdrop, .box').animate({
                    'opacity': '.50'
                }, 300, 'linear');
                $('.box').animate({
                    'opacity': '1.00'
                }, 300, 'linear');
                $('.backdrop, .box').css('display', 'block');
            });

            $('.close').click(function () {
                close_pop();
            });

            $('.backdrop').click(function () {
                close_pop();
            });
        }, 20000);
    }
});


function close_pop() {
    $('.backdrop, .box').animate({
        'opacity': '0'
    }, 300, 'linear', function () {
        $('.backdrop, .box').css('display', 'none');
    });

    $.cookie('hide', true);
    return false;
}

/*!
 * jQuery Cookie Plugin v1.3.1
 * https://github.com/carhartl/jquery-cookie
 *
 * Copyright 2013 Klaus Hartl
 * Released under the MIT license
 */
(function (factory) {
    if (typeof define === 'function' && define.amd) {
        // AMD. Register as anonymous module.
        define(['jquery'], factory);
    } else {
        // Browser globals.
        factory(jQuery);
    }
}(function ($) {

    var pluses = /\+/g;

    function raw(s) {
        return s;
    }

    function decoded(s) {
        return decodeURIComponent(s.replace(pluses, ' '));
    }

    function converted(s) {
        if (s.indexOf('"') === 0) {
            // This is a quoted cookie as according to RFC2068, unescape
            s = s.slice(1, -1).replace(/\\"/g, '"').replace(/\\\\/g, '\\');
        }
        try {
            return config.json ? JSON.parse(s) : s;
        } catch (er) {}
    }

    var config = $.cookie = function (key, value, options) {

        // write
        if (value !== undefined) {
            options = $.extend({}, config.defaults, options);

            if (typeof options.expires === 'number') {
                var days = options.expires,
                    t = options.expires = new Date();
                t.setDate(t.getDate() + days);
            }

            value = config.json ? JSON.stringify(value) : String(value);

            return (document.cookie = [
            config.raw ? key : encodeURIComponent(key),
                '=',
            config.raw ? value : encodeURIComponent(value),
            options.expires ? '; expires=' + options.expires.toUTCString() : '', // use expires attribute, max-age is not supported by IE
            options.path ? '; path=' + options.path : '',
            options.domain ? '; domain=' + options.domain : '',
            options.secure ? '; secure' : ''].join(''));
        }

        // read
        var decode = config.raw ? raw : decoded;
        var cookies = document.cookie.split('; ');
        var result = key ? undefined : {};
        for (var i = 0, l = cookies.length; i < l; i++) {
            var parts = cookies[i].split('=');
            var name = decode(parts.shift());
            var cookie = decode(parts.join('='));

            if (key && key === name) {
                result = converted(cookie);
                break;
            }

            if (!key) {
                result[name] = converted(cookie);
            }
        }

        return result;
    };

    config.defaults = {};

    $.removeCookie = function (key, options) {
        if ($.cookie(key) !== undefined) {
            // Must not alter options, thus extending a fresh object...
            $.cookie(key, '', $.extend({}, options, {
                expires: -1
            }));
            return true;
        }
        return false;
    };

}));

DEMO: JavaScript jsFiddle

HTML

<div class="popupbox" style="display: none;">
    <div class="backdrop box"> 
        <span>Hello World I am a popup.</span>
        <input type="button" class="close" value="Close" onclick="close_pop()" />
    </div>
</div>

JS

function close_pop() {
    $('.backdrop, .box').animate({
        'opacity': '0'
    }, 300, 'linear', function () {
        $('.backdrop, .box').css('display', 'none');
    });

    setCookie('hide', true, 365);
    return false;
}

function getCookie(c_name) {
    var c_value = document.cookie;
    var c_start = c_value.indexOf(" " + c_name + "=");
    if (c_start == -1) {
        c_start = c_value.indexOf(c_name + "=");
    }
    if (c_start == -1) {
        c_value = null;
    } else {
        c_start = c_value.indexOf("=", c_start) + 1;
        var c_end = c_value.indexOf(";", c_start);
        if (c_end == -1) {
            c_end = c_value.length;
        }
        c_value = unescape(c_value.substring(c_start, c_end));
    }
    return c_value;
}

function setCookie(c_name, value, exdays) {
    var exdate = new Date();
    exdate.setDate(exdate.getDate() + exdays);
    var c_value = escape(value) + ((exdays == null) ? "" : "; expires=" + exdate.toUTCString());
    document.cookie = c_name + "=" + c_value;
}

window.onload=function () {
    if (!getCookie('hide')) {
        window.setTimeout(function () {
            $('.popupbox').show();
            $('.popupbox').ready(function () {
                $('.backdrop, .box').animate({
                    'opacity': '.50'
                }, 300, 'linear');
                $('.box').animate({
                    'opacity': '1.00'
                }, 300, 'linear');
                $('.backdrop, .box').css('display', 'block');
            });

            $('.close').click(function () {
                close_pop();
            });

            $('.backdrop').click(function () {
                close_pop();
            });
            //change 1000 to 20000 for 20 seconds
        }, 1000);
    }
}
abc123
  • 17,855
  • 7
  • 52
  • 82