Skip to content

Instantly share code, notes, and snippets.

@GarySwift
Last active May 12, 2022 21:14
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save GarySwift/ceca6a4e5b4af484a06caeb6c6104b1a to your computer and use it in GitHub Desktop.
Save GarySwift/ceca6a4e5b4af484a06caeb6c6104b1a to your computer and use it in GitHub Desktop.
Cookie Reusable Component in ES6
import { cookies } from './lib/cookies';
import modal from './lib/modal';
$(document).ready(function() {
modal(cookies);
});
const cookies = {
name: "username",
timeInDays: 1,
hello: function(name) {
return 'Hello ' + name;
},
setCookie: function(cname, cvalue, exdays) {
const d = new Date();
d.setTime(d.getTime() + (exdays * 24 * 60 * 60 * 1000));
let expires = "expires="+d.toUTCString();
document.cookie = cname + "=" + cvalue + ";" + "path=/";
// document.cookie = cname + "=" + cvalue + ";" + expires + ";path=/";
},
getCookie: function(cname) {
let name = cname + "=";
let ca = document.cookie.split(';');
for(let i = 0; i < ca.length; i++) {
let c = ca[i];
while (c.charAt(0) == ' ') {
c = c.substring(1);
}
if (c.indexOf(name) == 0) {
return c.substring(name.length, c.length);
}
}
return "";
},
checkCookie: function () {
let user = this.getCookie(this.name);
if (user != "") {
alert("Welcome again " + user);
} else {
user = prompt("Please enter your name:", "");
if (user != "" && user != null) {
this.setCookie("username", user, this.timeInDays);
}
}
}
}
export { cookies }
export default function(cookies) {
cookies.checkCookie();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment