ccs-digitalmarketplace-govuk-frontend
Version:
Digital Marketplace GOV.UK Frontend contains the code you need to start building a user interface for Digital Marketplace.
78 lines (58 loc) • 2.82 kB
JavaScript
import { getConsentCookie, setConsentCookie } from '../../helpers/cookie/cookie-functions'
import InitialiseAnalytics from '../analytics/init'
const CookieBanner = function ($module) {
this.$module = $module.get(0)
}
CookieBanner.prototype.init = function () {
this.$module.hideCookieMessage = this.hideCookieMessage.bind(this)
this.$module.showConfirmationMessage = this.showConfirmationMessage.bind(this)
this.$module.setCookieConsent = this.setCookieConsent.bind(this)
this.$module.cookieBanner = document.querySelector('.dm-cookie-banner')
this.$module.cookieBannerConfirmationMessage = this.$module.querySelector('.dm-cookie-banner--selection-made')
this.setupCookieMessage()
}
CookieBanner.prototype.setupCookieMessage = function () {
this.$hideLink = this.$module.querySelector('button[data-hide-cookie-banner]')
if (this.$hideLink) {
this.$hideLink.addEventListener('click', this.$module.hideCookieMessage)
}
this.$acceptCookiesLink = this.$module.querySelector('button[data-accept-cookies=true]')
if (this.$acceptCookiesLink) {
this.$acceptCookiesLink.addEventListener('click', () => this.$module.setCookieConsent(true))
}
this.$rejectCookiesLink = this.$module.querySelector('button[data-accept-cookies=false]')
if (this.$rejectCookiesLink) {
this.$rejectCookiesLink.addEventListener('click', () => this.$module.setCookieConsent(false))
}
this.showCookieMessage()
}
CookieBanner.prototype.showCookieMessage = function () {
// Show the cookie banner if policy cookie not set
const hasCookiesPolicy = getConsentCookie()
if (this.$module && !hasCookiesPolicy) {
this.$module.style.display = 'block'
}
}
CookieBanner.prototype.hideCookieMessage = function (event) {
if (this.$module) {
this.$module.style.display = 'none'
}
if (event.target) {
event.preventDefault()
}
}
CookieBanner.prototype.setCookieConsent = function (analyticsConsent) {
setConsentCookie({ analytics: analyticsConsent })
this.$module.showConfirmationMessage(analyticsConsent)
this.$module.cookieBannerConfirmationMessage.focus()
if (analyticsConsent) { InitialiseAnalytics() }
}
CookieBanner.prototype.showConfirmationMessage = function (analyticsConsent) {
const messagePrefix = analyticsConsent ? 'You’ve accepted analytics cookies.' : 'You told us not to use analytics cookies.'
this.$cookieBannerMainContent = document.querySelector('.dm-cookie-banner__button--main')
this.$cookieBannerConfirmationMessage = document.querySelector('.dm-cookie-banner__confirmation-message')
this.$cookieBannerConfirmationMessage.insertAdjacentText('afterbegin', messagePrefix)
this.$cookieBannerMainContent.setAttribute('hidden', 'hidden')
this.$module.cookieBannerConfirmationMessage.removeAttribute('hidden')
}
export default CookieBanner