N-State HTML Element

Posted at

10-State Example.
Click the number below:






code:
<!doctype html>
<html dir="ltr" lang="en-US">
<head>
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1"/>
<meta http-equiv="Content-Type" content="text/html;charset=UTF-8"/>
<meta name="viewport" content="width=device-width,height=device-height,initial-scale=1.0,minimum-scale=1.0,maximum-scale=1.0,user-scalable=no"/>
<style type="text/css" media="all">
html{
background: none lightblue;
}
div:before{content:attr(data-state);}

div:before{background:yellow; font-size:20pt;}
div[data-state="1"]:before{background:lightgreen;}
div[data-state="2"]:before{background:blue;}
div[data-state="3"]:before{background:red;}
div[data-state="3"]:before{background:purple; font-size:30pt;}
</style>
</head>
<body>
<div data-state="0"></div>
<script type="application/javascript">
document.querySelector('[data-state]').onclick=function(e){
e = e.target;
e.setAttribute("data-state",
(Number(e.getAttribute("data-state")) + 1) % 10
);
};
</script>
</body>
</html>





- As you can see the N in the "N-State" is set by modulus-operation, which can (also) be set as an attribute (for example data-state-max).

The dynamic-content is set using a little CSS trick,
in which you use the :before together with attr and content, this saves using JavaScript to change the content too....


This can be applied to any element, but it will work best with non-state elements (for example stuff that are not checkbox or select/option, since it will be very confusing and really bad UI-design practice).