Last active
April 30, 2019 20:28
-
-
Save SethVandebrooke/2f7336bdc72d2450486c75d4c85d23a9 to your computer and use it in GitHub Desktop.
Manage user input with little to no set up
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
// Get value of input element | |
// SYNTAX: $IN.elementID | |
var username = $IN.username(); | |
// Listen for when the value changes | |
$IN.username.observe(function(value){ | |
console.log("value changed to:" + value); | |
}); | |
// Set input element value | |
$IN.username("NewUsername"); | |
*/ | |
var Wieldable = function(v){ | |
var d, l = [], t = function () { | |
for (var i = 0; i < l.length; i++) { | |
if (typeof l[i] === "function") { | |
l[i](d); | |
} | |
} | |
}; | |
var wieldable = function (v) { | |
if (v != undefined) { | |
d = v; | |
t(); | |
} | |
return d; | |
}; | |
wieldable.observe = function (f) { | |
if ("function" === typeof f) { | |
l.push(f); | |
return { | |
stop: function () { | |
return l.splice(l.indexOf(f),1) | |
}, | |
start: function () { | |
return l.push(f); | |
} | |
}; | |
} | |
}; | |
wieldable.bind = function (element,eventName) { | |
eventName = eventName.trim(); | |
if (eventName.replace("key","") !== eventName && | |
eventName.replace("-","") !== eventName) { | |
eventName = eventName.split("-"); | |
var key = eventName[0]; | |
eventName = eventName[1]; | |
} | |
element.addEventListener(eventName, function(e) { | |
if (key !== undefined) { | |
if (key == e.key || key == e.code || key == e.which) { | |
wieldable(element.value); | |
} | |
} else { | |
wieldable(element.value); | |
} | |
}); | |
if (element.value) wieldable(element.value); | |
return wieldable.observe(function(text) { | |
element.value = text; | |
}); | |
} | |
wieldable.refresh = t; | |
wieldable(v); | |
return wieldable; | |
}; | |
(function (w){ | |
var inputs = {}; | |
document.querySelectorAll("input, select, textarea").forEach(function (element, index) { | |
var id = element.id; | |
if (!!id) { | |
inputs[id] = new Wieldable(); | |
inputs[id].bind(element, "change"); | |
inputs[id].bind(element, "click"); | |
inputs[id].bind(element, "keyup"); | |
} | |
}); | |
w.$IN = inputs; | |
})(window); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment