Show/Hide form using cookie
by alano
HTML
<p class="promo1">
Answer some questions. You will have 2 minutes to complete the questions.
<button id="showQ">Show</button>
</p>
<div id="containerQ" class="promo1">
<p>Time remaining: <span></span></p>
<!-- Questions and Answers -->
Question #1<br />
Question #2<br />
...<br />
<button id="doneQ">Done</button>
</div>
<br /><br /><br />
<button id="resetQ">Reset Cookie (Test Only)</button>
CSS
.promo1 { display:none; }
#containerQ p { color:Red; }
#containerQ p span { font-size:20px; font-weight:bold; }
JavaScript
var remaining = 2 * 60 * 1000;
var $timer, tTotal, tInterval;
$(document).ready(function() {
$("#resetQ").click(function() { //for test purposes
delCookie("promo1");
alert("Now, please refresh the page");
});
if (!getCookie("promo1")) {
$("p.promo1").show("slow");
$("#showQ").on("click", function() {
if (confirm("Are you sure you wish to start now?")) {
//start questionnaire
setCookie("promo1", "started", 365);
$("#containerQ").show("slow");
startTimer();
$("#doneQ").one("click", function() {
submitAnswers();
});
}
});
}
});
function startTimer() {
tTotal = window.setTimeout(submitAnswers, 2 * 60 * 1000);
$timer = $("#containerQ p span").text("02:00:000");
tInterval = window.setInterval(timerUpdate, 1000);
}
function timerUpdate() {
remaining -= 1000;
$timer.text(remaining.toMillisecondString());
}
function submitAnswers() {
window.clearTimeout(tTotal);
window.clearInterval(tInterval);
$(".promo1").hide("slow");
//send answers to database here
alert("Form has been submitted. Thank you");
}
//MY HELPER METHODS...
Number.prototype.toMillisecondString = function () {
var partMultipliers = [{d:60000,p:100}, {d:1000,p:100}, {d:1,p:1000}];
var remainder = parseInt(this);
return partMultipliers.reduce(function (prev, m, idx) {
var part = Math.floor(remainder / m.d);
remainder -= (part * m.d);
var quo = (part + m.p).toString().substr(1);
return prev + ((idx == 0) ? "" : ":") + quo;
}, "");
}
//MY COOKIE LIBRARY...
function delCookie(name) {
setCookie(name, "", -1);
}
function setCookie(name, value, days) {
var expires = "";
if (days) {
var date = new Date();
date.setDate(date.getDate() + days);
expires = "; expires=" + date.toUTCString();
}
...