#AD 50 Projects In 50 Days (HTML, CSS & JavaScript) - Sharpen your skills by building 50 mini projects!

Display a message to returning visitors using a JavaScript cookie

By Michael Burrows | Last modified August 28th 2020 | GitHub Source Code [GitHub]

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); });
Code language: JavaScript (javascript)

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); } }
Code language: JavaScript (javascript)

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=/"; }
Code language: JavaScript (javascript)

Now if you refresh the browser you’ll see a message which we can pretty up with a bit of 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; }
Code language: CSS (css)

Related Posts