JSFiddle - React, Tailwind, and code Playground
by Nikita
HTML
<script src="https://rawgithub.com/carhartl/jquery-cookie/master/jquery.cookie.js"></script>
<div id="statuses"> <a id="first" class="status">Waiting</a>
<a id="second" class="status">Waiting</a>
<a id="third" class="status">Waiting</a>
<a id="fourth" class="status">Waiting</a>
<!--
<a id="fifth" class="status">Waiting</a>
<a id="sixth" class="status">Waiting</a>
<a id="seventh" class="status">Waiting</a>
<a id="eighth" class="status">Waiting</a>
-->
</div>
<input type="button" id="reset" value="Reset" />
CSS
div#statuses {
width: 90px;
}
a.status {
background-color: #ff0;
cursor: pointer;
padding: 5px 10px;
margin: 5px 0;
border-radius: 5px;
border: 2px solid #777;
display:block;
text-align: center;
}
a.status.selected {
background-color: #0f0;
border: 2px solid #ccc;
}
JavaScript
var COOKIE_NAME = "selection";
function getObjectProperties(obj) {
var keys = [];
for (var k in obj) keys.push(k);
return keys;
}
function deserialize() {
$.cookie.json = true;
//read object from cookies
var selection = $.cookie(COOKIE_NAME);
console.log(selection);
if (selection !== undefined) {
//go over each property (first, second, ...)
$.each(getObjectProperties(selection), function (index, element) {
//find button by id
var $elem = $("#" + element);
//read selection value for button
var isSelected = selection[element];
if (isSelected) {
//mark button as selected
$elem.addClass("selected").html("Ready");
}
});
}
}
function serialize() {
//initialize empty object
var selection = {};
//go over each button
$(".status").each(function (index) {
var $this = $(this);
//add new property to object and assigning value to it ({first:false, second:true /*,....*/})
selection[$this.attr("id")] = $this.hasClass("selected");
});
console.log(selection);
//save object to cookie
$.cookie(COOKIE_NAME, selection);
}
$(document).on("click", ".status", function (e) {
var $this = $(this);
$this.toggleClass("selected");
var isSelected = $this.hasClass("selected");
$this.html(isSelected ? "Ready" : "Waiting");
serialize();
});
$(document).on("click", "#reset", function (e) {
$(".status").removeClass("selected").html("Waiting");
serialize();
});
deserialize();