Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>Here's a <em>simple</em> CookieManager object I wrote to demonstrate how you can accomplish this. There is a much more robust version of this type of thing in the (MDN document.cookie docs)[https://developer.mozilla.org/en-US/docs/Web/API/document.cookie] but this should help you get a fundamental understanding. You can/should extend this to allow for domain, path, expiration, etc.</p> <p>When you first visit the page, you will see the countdown message. When the countdown completes, jquery is used to replace the contents (lines 48-51) of the <code>#content</code> div. When you refresh the page, the content will be shown immediately if the <code>visited</code> cookie exists.</p> <pre><code>&lt;!DOCTYPE html&gt; &lt;html&gt; &lt;head&gt; &lt;title&gt;document.cookie Example&lt;/title&gt; &lt;/head&gt; &lt;body&gt; &lt;div id="content"&gt;&lt;p&gt;Your content will be shown in &lt;span id="countdown"&gt;15&lt;/span&gt; seconds&lt;/p&gt;&lt;/div&gt; &lt;a href="#" class="delete"&gt;Remove Cookie&lt;/a&gt; &lt;script type="text/javascript" src="http://code.jquery.com/jquery-1.10.2.min.js"&gt;&lt;/script&gt; &lt;script type="text/javascript"&gt; $(document).ready(function() { var main = new Main(); main.init(); }); var Main = function() { var _this = this, cookieMngr = new CookieManager(), countInterval = false, count = 15; _this.init = function() { if(cookieMngr.getCookie("visited")) { _this.addContent(); } else { countInterval = setInterval(_this.updateCountdown, 1000); } $(".delete").on("click", function(evt) { evt.preventDefault(); cookieMngr.deleteCookie("visited"); document.location = document.location; }); }; _this.updateCountdown = function() { if(count &gt; 0) { count--; $("#countdown").text(count); } else { clearInterval(countInterval); countInterval = false; cookieMngr.setCookie("visited", "yes"); _this.addContent(); } }; _this.addContent = function() { var newContent = $(document.createElement("div")).html("&lt;p&gt;This is the content you've been waiting for.&lt;/p&gt;"); $("#content").empty().append(newContent); }; return _this; }; var CookieManager = function() { _this = this; _this.setCookie = function(cookieKey, cookieValue) { var cookieStr = cookieKey+"="+cookieValue; document.cookie = cookieStr; }; _this.getCookie = function(cookieKey) { var regex = new RegExp(cookieKey+"\=([^;]+)"); var cookie = document.cookie.match(regex); if(cookie !== null) { return cookie[1]; } else { return false; } }; _this.deleteCookie = function(cookieKey) { document.cookie = cookieKey+"=; expires=Thu, 01 Jan 1970 00:00:00 GMT"; }; return _this; }; &lt;/script&gt; &lt;/body&gt; &lt;/html&gt; </code></pre>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload