MysteryWhy
MysteryWhy

Reputation: 13

how to use cookies to prevent a jquery popup to after click action

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

Upvotes: 1

Views: 6846

Answers (1)

abc123
abc123

Reputation: 18753

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);
    }
}

Upvotes: 2

Related Questions