Cookies are small strings of data stored on your computer that can be accessed by a web browser.
By using cookies we can detect if a visitor has visited a website before from the same browser.
This can be useful for showing a customised message or directing visitors to a special promotion.
NOTE β Chrome doesnβt store cookies from pages loaded on the local file system (file://).
Letβs start by defining our cookie name and calling a function to check if the cookie already exists.
document.addEventListener("DOMContentLoaded", function () {
const userCookieName = "returningVisitor";
checkUserCookie(userCookieName);
});
If the cookie exists then insert HTML with our message otherwise call a function to create the cookie.
function checkUserCookie(userCookieName) {
const regEx = new RegExp(userCookieName, "g");
const cookieExists = document.cookie.match(regEx);
if (cookieExists != null) {
document.body.insertAdjacentHTML(
"beforeend",
'<div id="welcome">Welcome back friend! Check out our latest thing <a href="#">HERE</a></div>'
);
} else {
createUserCookie(userCookieName);
}
}
Lastly we create the cookie using document.cookie with our cookie name, value and an expiry date.
function createUserCookie(userCookieName) {
const userCookieValue = "Yes";
const userCookieDays = 7;
let expiryDate = new Date();
expiryDate.setDate(expiryDate.getDate() + userCookieDays);
document.cookie = userCookieName + "=" + userCookieValue +"; expires=" + expiryDate.toGMTString() + "path=/";
}
Now if you refresh the browser you should see the message which we can pretty up with some CSS.
#welcome {
position: fixed;
bottom: 0;
width: 100%;
padding: 10px 0;
background: rgb(14, 108, 170);
color: #fff;
text-align: center;
}
#welcome a {
color: #fff;
}
Top comments (2)
Nice post. Thanks!
Cool stuff