JSFiddle - React, Tailwind, and code Playground
by JThomas
HTML
<h4>Single field</h4>
<input id="check" type="checkbox" />
<input type="text" data-reveal="when #check is true" />
<h4>Multiple fields</h4>
<input id="name" type="text" />
<input id="address" type="text" data-reveal="when #name is a" />
<input id="phone" type="text" data-reveal="when #address is 123" />
<button type="button" data-reveal="when #phone is 319">Submit</button>
JavaScript
window.Reveal = function (window) {
'use strict'
function reveal() {
var self = this;
//Collection of parsed elements
self.elems = [];
//Define the property we should check for a given input type
self.props = {
text: 'value',
checkbox: 'checked',
radio: 'checked'
}
function init() {
parseElements();
}
function parseElements() {
var hits = Array.prototype.slice.call(document.querySelectorAll('[data-reveal]'));
hits.forEach(function (el) {
var expr = el.getAttribute("data-reveal");
el.removeAttribute('data-reveal');
el.setAttribute('style', 'display: none');
self.elems.push(parseConfig(expr, el));
});
}
function parseConfig(expr, el) {
var words = expr.split(' '),
c = { el: el };
for (var i = 0, word; word = words[i++];) {
switch (word) {
case 'when':
c.for = document.querySelector(words[i]);
c.for.addEventListener('change', function (e) { handler(c); });
c.for.addEventListener('keyup', function (e) { handler(c); });
break;
case 'is':
c.condition = words[i];
break;
}
}
return c;
}
function handler(c) {
var prop = self.props[c.for.type],
value = c.for[prop];
//TODO: Find another way to check for boolean types
if (value == true || value == c.condition) {
c.el.removeAttribute('style');
} else {
c.el.setAttribute('style', 'display: none;');
}
}
...