Skip to content

Instantly share code, notes, and snippets.

@wwwebman
Last active November 16, 2017 17:35
Show Gist options
  • Save wwwebman/6cbf338a5b65f82dda896e2ad7eb4085 to your computer and use it in GitHub Desktop.
Save wwwebman/6cbf338a5b65f82dda896e2ad7eb4085 to your computer and use it in GitHub Desktop.
Set and get cookie with JavaScript (JS, SCSS, HTML)
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
</head>
<body>
<div class="m-cookies">
<div class="container">
<div class="row">
<div class="col-sm-9"><p>Find out about the cookies - <a href="http://www.sussex.ac.uk/about/website/cookies" rel="nofollow noreferrer noopener" target="_blank">link</a></p></div>
<div class="col-sm-3"><button type="button" class="btn">Accept</button></div>
</div>
</div>
</div>
</body>
</html>
@szujak
Copy link

szujak commented Nov 16, 2017

const COOKIE_NAME = 'cookie'
const COOKIE_VALUE = 'accepted'
const COOKIE_EXPIRE = 365

const mCookie = document.querySelector('.jsCookieInfo')
const mCookieBtn = document.querySelector('.jsCookieInfo button')

const getDate = function (exdays = 365) {
  const date = new Date()

  date.setTime(date.getTime() + (exdays * 24 * 60 * 60 * 1000))

  return date
}

const getCookieContent = function (name, value, date) {
  return `${name}=${value}; expires=${date.toUTCString()}; domain=${window.location.hostname}; path=/`
}

const setCookie = function (name = COOKIE_NAME, value = COOKIE_VALUE, exdays = COOKIE_EXPIRE) {
  document.cookie = getCookieContent(name, value, getDate(exdays))
}

const getCookie = function (name = COOKIE_NAME, value = COOKIE_VALUE) {
  return document.cookie.split('; ').indexOf(`${name}=${value}`) > 0
}

// Set cookies onAccept
mCookieBtn. addEventListener('click', function () {
  mCookie.style.display = 'none'
  setCookie()
})

// Show/hide coockie
if (getCookie('cookie')) {
  mCookie.style.display = 'none';
} else {
  mCookie.style.display = 'block';
}

@wwwebman
Copy link
Author

Looks good! Thanks!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment