0

I have been trying to create a simple cookie box notification, and i actually would like to use this specific idea

The problem is that when i run this js in my footer, and i just click the 'yes' or 'no' then after refreshing the page i see again from the beginning the cookie box. I just want to set there a very simple expiration date like 10 days for example, and nothing more, and when i click depend on the answer,to function correct.

I am really not good with js so if anyone can help me , i would appreciate it. :)

!(function() {
var e = function(e, t, o) {
(this.text = e),
  (this.acceptText = t),
  (this.denyText = o),
  (this.element = null),
  this.init();
};
(e.prototype = {
init: function() {
  this.create(), this.load(), this.actions();
},
load: function() {
  null === localStorage.getItem("cookie-box-accepted") && this._show();
},
actions: function() {
  var e = document.querySelector("#cookie-box-accept"),
    t = document.querySelector("#cookie-box-deny"),
    o = this;
  e.addEventListener(
    "click",
    function(e) {
      e.preventDefault(),
        localStorage.setItem("cookie-box-accept", "yes"),
        o._hide();
    },
    !1
  ),
    t.addEventListener(
      "click",
      function(e) {
        e.preventDefault(),
          localStorage.setItem("cookie-box-deny", "no"),
          o._hide();
      },
      !1
    );
},
create: function() {
  var e = document.createElement("div");
  this.element = e;
  var t =
    "<div id='cookie-box-wrap'><div id='cookie-box-text'>" +
    this.text +
    "</div>";
  (e.id = "cookie-box"),
    (t +=
      "<div id='cookie-box-btns'><button type='button' id='cookie-box-accept'>" +
      this.acceptText +
      "</button>"),
    (t +=
      "<button onclick=deleteAllCookies() type='button' id='cookie-box-deny'>" +
      this.denyText +
      "</button></div>"),
    (t += "</div>"),
    (e.innerHTML = t),
    document.body.appendChild(e);
},
_show: function() {
  var e = this;
  (e.element.style.display = "block"),
    setTimeout(function() {
      e.element.className = "visible";
    }, 500);
},
_hide: function() {
  var e = this;
  (e.element.className = ""),
    setTimeout(function() {
      e.element.style.display = "none";
    }, 500);
}
  }),
document.addEventListener("DOMContentLoaded", function() {
  new e(
    "This website uses &laquo;cookies&raquo; to give you the best experience when you visit. You can manage or block them <a href='https://www.aboutcookies.org/how-to-control-cookies/' target='_blank'>in your browser settings</a>. <span id='open'><svg height='100' width='35'><text x='0' y='0' fill='#c9770c' transform='rotate(90 1,10)'>Cookies</text>Your browser does not support inline SVG.</svg></span> Do you accept cookies?",
    "Yes",
    "No"
  );
});
})();
var sheet = (function() {
var e = document.createElement("style");
return (
e.appendChild(
  document.createTextNode(
    "#cookie-box{position:fixed;bottom:1px;left:1px;width:99%;max-width:290px;min-height:3em;background:#f1f1f1;border:dotted 1px #555;color:#555;z-index:10000000000;display:none;transition:all .5s ease-in;transform:scaleY(0)}#cookie-box.visible{transform:scaleY(1)}#cookie-box{margin-left:-293px}#cookie-box:hover{margin-left:1px}#cookie-box-wrap{margin:0 auto;max-width:285px;text-align:center}#cookie-box-text{padding:17px 3px 7px;font-family:Arial;font-size:13px;line-height:17px;margin-bottom:5px}#cookie-box-text a{color:#c9770c;text-decoration:underline;text-decoration-style:dotted}#cookie-box-btns{margin:15px auto}#cookie-box-btns button{border-radius:1px;border:none;padding:7px 33px;font-size:13px!important;line-height:17px;font-family:Arial;color:#fff;text-transform:uppercase;cursor:pointer;margin-right:7px;transition:all .5s ease-in}#cookie-box-btns button:hover{background-color:grey}button#cookie-box-accept{background:olivedrab}button#cookie-box-deny{background:#c9770c;}#open{ float:right;margin-top:-25px;margin-right:-40px;color:black;font-size:23px;cursor:all-scroll;background:#f1f1f1;border:dotted 1px #555;border-left:none}"
  )
),
document.head.appendChild(e),
e.sheet
);
})();
function deleteAllCookies() {
(document.cookie = "=; expires=Fri, 31 Dec 2000 23:59:59 UTC; path=/"),
alert(
  "I am cookie with an expiry date 31 Dec 2000 23:59:59. I don't live after: " +
    document.cookie
);
}

EDIT ------------------------------------

The idea of code i have tried

load: function() {
null === checkCookie("cookie-box-accept") && this._show();
},
actions: function() {
var e = document.querySelector("#cookie-box-accept"),
t = document.querySelector("#cookie-box-deny"),
o = this;
e.addEventListener(
"click",
  function(e) {
  e.preventDefault(),
    setcookie("cookie-box-accept", 'visited',time()+60*60*24*31, "yes"),
    o._hide();
 },
 !1
  ),
  t.addEventListener(
   "click",
   function(e) {
    e.preventDefault(),
       unsetcookie("cookie-box-deny", "no"),
       o._hide();
   },
   !1
 );
},

unfortunately not working :(

  • You just need to create a cookie with an expiration date of +10 days and check if the cookie is present before displaying the cookie message. Can you provide the code you manage to produce so far? – Dexter0015 May 25 '18 at 14:51
  • Hello Dexter0015, thank you for your reply :) Actually i didn't built a code, i just used the one from another delevoper from codepen.io/anon/pen/gzVmrP?editors=0010#0 I am totally unfamiliar with js but i managed to use this simple js code, putting it to my themes footer running. The problem is that the code must have some problem as it (most probably) doesn't function correct. When i click on 'yes' or 'no' then the box notification close. But if i just refresh the page it is there appearing again. – Honoluluman May 26 '18 at 14:00
  • I updated my topic with the full code. As you can see it has the javascript part and also the css part (css code i am familiar). In the javascript part there must be some problem i think. Please if you can have a look and tell me if you find something wrong. Thank you again. – Honoluluman May 26 '18 at 14:00
0

I get it this is just a typo.

But just to be clear, this code doesn't use cookie to store the user choice, but localStorage, which is something different but can be used to do so here.

So after testing the given code it work, look at this 2 metbhods:

load: function() {
  null === localStorage.getItem("cookie-box-accepted") && this._show();
},
actions: function() {
  var e = document.querySelector("#cookie-box-accept"),
    t = document.querySelector("#cookie-box-deny"),
    o = this;
  e.addEventListener(
    "click",
    function(e) {
      e.preventDefault(),
        localStorage.setItem("cookie-box-accept", "yes"),
        o._hide();
    },
    !1
  ),
    t.addEventListener(
      "click",
      function(e) {
        e.preventDefault(),
          localStorage.setItem("cookie-box-deny", "no"),
          o._hide();
      },
      !1
    );
},

The load method is responsible of testing if the cookie choice is stored in the localStorage and if not, display the cookie block. And the actions method add listeners on choices buttons to create the value of the choice to store in the localStorage.

The value is created as a key > value, and the problem in your code is that the name of the value the load method is looking for isn't the same as the one created by the actions method :

The load method is looking for a value corresponding to a key named "cookie-box-accepted" where the actions method store it on a key named "cookie-box-accept"

So if you change the key name the load method is looking for for the same as the actions method creates, it will work as intended.

EDIT TO ANSWER YOUR OTHER QUESTIONS ------------------------------------

Ok, so go check the link I gave you about localStorage, it's really well explain and concise.

To answer your questions now:

1 - The localStorage is not build on the idea of expiration (unlike the cookies are) so it won't be deleted automatically, you would have to implement a way, in your code, to test the age of the data stored and remove it when it's too old. See this answer: https://stackoverflow.com/questions/2326943/when-do-items-in-html5-local-storage-expire

2 - As explained in the link I gave you (about localStorage), there is 2 "types" of webStorage :

HTML web storage provides two objects for storing data on the client:

window.localStorage - stores data with no expiration date window.sessionStorage - stores data for one session (data is lost when the browser tab is closed)

So you can use sessionStorage in place of localStorage but then the user will have to reselect his preferences every time he come back to your website after quit/restart his browser.

Note that you can remove manualy a localStorage data from your browser through it's developer console :

  • click "F12" on Chrome/Firefox
  • It will display the developer toolbar (which is fulll of useful tools btw)
  • navigate to the "Application" tab on the left column, you should see a "Storage" section, then "LocalStorage", ...

Here you can see the localStorage data stored by the domaine (localStorage data are link to domaine like a cookie), and can remove some. BUT as it has to be done manually I would reserve that to the developpement/debug sessions (a better way would to to implement it in your code as mentionned erlier) as common user will never do it of course (and should no be able to anyway).

3 - In my own opinion, localStorage is a great mecanism, but in this particular case, I would prefere cookie because it's better fit the expected behaviour, and as it is build on the idea of expiration, you just have to set it when you create it and it will be automatically removed by your browser when expired (or sooner if the user remove the cookie manually...).

  • Thank you Dexter for your good explanation :) I think the error is minor, and i will test it to see how it works. But your explanation lead me in 3 other questions regarding the code. 1. Is it possible to add to this code some kind of expiration date of the session, for example 10 days and then deletes ?! – Honoluluman May 28 '18 at 14:29
  • 2. If the entire idea of the code is not with cookie, but with localStorage as you mentioned, if i just clear my browsers cookies, will it be deleted, the session or not? I mean since it is not a cookie that is stored in the browser, then how can i test this multiple times, in my own browser? 3. Is it ok to use the method of localStorage instead of cookie?My point is to, just have a simple notification for the user. Thank you very much for your time! :) – Honoluluman May 28 '18 at 14:29
  • I just edit my answer to address your questions, hope it helps. – Dexter0015 May 29 '18 at 9:18
  • Hello Dexter, Thank you so much for the explanation. You are right , i saw after i wrote you, about the localstorage explination page w3schools.com/Html/html5_webstorage.asp . It is written there clearly. So the way i see it, i have 2 options, either i just substitute in the code where ever is writen ''localStorage'' -> ''sessionStorage'' with the bad side that the user will have to reselect his preferences every time he come back to the website, or try to create a cookie with expiration date to the code, which is better and more advance for this simple purpose as you mentioned. – Honoluluman May 30 '18 at 7:59
  • I have tried to experiment with code for creating the cookie * see update also in my description, but no luck :( as i am not good :( – Honoluluman May 30 '18 at 7:59

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.