JSFiddle - React, Tailwind, and code Playground
by Mustafa Oeztuerk
HTML
<div class="container">
<div class="buttons">
<div class="item" id="a1" data-id="1" rel="a">1</div>
<div class="item" id="b1" data-id="1" rel="b">2</div>
<div class="item" id="c1" data-id="1" rel="c">3</div>
<div class="item" id="d1" data-id="1" rel="d">4</div>
<div class="item" id="e1" data-id="1" rel="e">5</div>
<div class="item" id="f1" data-id="1" rel="f">6</div>
</div>
<div class="add" id="add1">
<div class="sum">0</div>
</div>
</div>
CSS
.container {
width: 100%;
max-width: 550px;
background-color: #d8dbdf;
margin: 0px auto;
border-radius: 2px;
-webkit-border-radius: 2px;
-moz-border-radius: 2px;
position: relative;
margin-top: 50px;
overflow: hidden;
font-family: helvetica, arial, sans-serif;
-moz-osx-font-smoothing: grayscale;
-webkit-font-smoothing: antialiased;
}
.buttons {
width: 100%;
padding: 8px;
box-sizing: border-box;
float: left;
overflow: hidden;
}
.item {
width: 30px;
height: 20px;
float: left;
text-align: center;
line-height: 25px;
margin-right: 5px;
}
.add {
width: 100%;
float: left;
padding: 10px;
}
.item:nth-child(2n+1) {
background-color: red;
}
.pa {
width: 30px;
height: 30px;
background-color: blue;
float: left;
margin-right: 5px;
}
.pb {
width: 30px;
height: 30px;
background-color: green;
float: left;
margin-right: 5px;
}
.pc {
width: 30px;
height: 30px;
background-color: pink;
float: left;
margin-right: 5px;
}
.pd {
width: 30px;
height: 30px;
background-color: yellow;
float: left;
margin-right: 5px;
}
.pe {
width: 30px;
height: 30px;
background-color: black;
float: left;
margin-right: 5px;
}
.pf {
width: 30px;
height: 30px;
background-color: orange;
float: left;
margin-right: 5px;
}
JavaScript
$(document).ready(function() {
var lastState;
var lastStatei = '';
$("body").on("click", ".item", function() {
var dataid = $(this).attr("data-id");
var REL = $(this).attr("rel");
var map = {
'na': 'pli',
'nb': 'plo',
'nc': 'phi',
'nd': 'pwo',
'ne': 'pwo',
'nf': 'pc'
};
var dict = {
'a': 'pa',
'b': 'pb',
'c': 'pc',
'd': 'pd',
'e': 'pe',
'f': 'pf'
};
if (lastState) {
// switch off
if (dict[lastState]) {
if ($('#sum' + dataid).text() == 0) {
$('#' + dict[lastState] + dataid).remove();
}
}
}
if (lastState === REL) {
lastState = undefined;
} else {
// switch on
if (dict[REL]) {
if (!$('#' + dict[REL] + dataid).length) {
$('#add' + dataid).prepend('<div class="' + dict[REL] + '" id="' + dict[REL] + dataid + '"></div>');
}
}
lastState = REL;
}
function change(state) {
var temp = state,
not = 'n';
if (state.substring(0, 1) === 'Un') {
temp = state.substring(1);
not = '';
}
if (['a', 'b', 'c', 'd', 'e', 'f'].indexOf(temp) !== -1) {
$('#' + temp + dataid).attr('rel', not + temp);
}
return not + temp;
}
// usage always both together:
change(lastStatei); // to reset the last state
lastStatei = change(REL); // call change and save the actual state
});
});