简体   繁体   中英

Cookie message show only once per click / submit button accept

I need help for cookies message popup. I want that message show only once per user CLICK accept. Here is code: https://jsfiddle.net/bz8ur3wu/1/

 $(document).ready(function(){ $("button").click(function(){ $(".cookie").fadeOut(); }); });
 .cookie{width:100%;padding:20px;background:rgb(231, 231, 231);bottom:0;left:0;position:fixed;}
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div class="cookie"> This website use cookies. <button>accept</button> </div>

As alternative solution I suggest localstorage . Look for a cookieconsent value and add a class to the body if you've found it; otherwise set the value when the user click the button.

$(document).ready(function(){
    if (!!localStorage.getItem("cookieconsent")) {
        document.body.classList.add("cookieconsent")
    } 
    else {
        $("button").click(function() {
            localStorage.setItem("cookieconsent", "ok")
            $(".cookie").fadeOut();
        });
    }
});

then in your CSS show the .cookie element only if user didn't accept before, that is, if the body has not the .cookieconsent class

.cookie { 
    display: none; }

body:not(.cookieconsent) .cookie {
    display: block;
}

I created a little script to include in every project. It creates a cookie and check if exists or not so show or hide a div with id #cookie-notice

I think it's a good start. then you can personalize as you wish

 var myProj = myProj || {} myProj.cookiePolicy = function (__M) { var cookiePolicy = document.querySelector('#cookie-notice'), acceptCookieBtn = cookiePolicy.querySelector('#cn-accept-cookie'), closeCookiePolicy = cookiePolicy.querySelector('a.close-button'); closeCookiePolicy.addEventListener('click', function (ev) { ev.preventDefault(); acceptCookie(); }); document.querySelector('body').addEventListener('click', function (ev) { acceptCookie(); }); window.addEventListener('scroll', function (ev) { acceptCookie(); }); acceptCookieBtn.addEventListener('click', function (ev) { ev.preventDefault(); acceptCookie(); }); if (document.cookie.indexOf('cookie_notice_accepted') === -1) { cookiePolicy.classList.add('show'); } function acceptCookie() { if (document.cookie.indexOf('cookie_notice_accepted') === -1) { cookiePolicy.classList.add('show'); // set cookie var d = new Date(); d.setTime(d.getTime() + (365 * 24 * 60 * 60 * 1000)); document.cookie = 'cookie_notice_accepted=true' + ';expires=' + d.toGMTString(); } if(cookiePolicy){ cookiePolicy.parentNode.removeChild(cookiePolicy); cookiePolicy = null; } } }(myProj);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM