JSFiddle - React, Tailwind, and code Playground
HTML
<input type="text" id="t"><button>Say my name</button><br><button>Output all variables again</button><br><br>
JavaScript
// An object in which to store variables, which also writes variables to a given element as you create them.
// Include this code at the top of your javascript.
var VariableStore = function(outputElement) {
this.store = {};
this.outputElement = outputElement;
};
VariableStore.prototype = {
create : function(key, value) {
this.store[key] = value;
this.output(key);
},
get : function(key) {
return this.store[key];
},
destroy : function(key) {
delete this.store[key];
},
output : function(key) {
var value = this.store[key];
var outputText = (typeof value === "object" && value.constructor === Object && window.JSON) ? JSON.stringify(value) : value;
this.outputElement.appendChild(document.createTextNode(outputText));
this.outputElement.appendChild(document.createElement("br"));
},
outputAll : function() {
for(var key in this.store) {
this.output(key);
}
}
};
// Here's how to use the object above.
// 1. Create a new instance of VariableStore, here called v. This only needs to be done once in your script, just underneath the VariableStore object above.
var v = new VariableStore(document.body);
// 2. This creates three new variables. They will be automatically outputted to the output element when they are created. This code can go anywhere in your script underneath the first two steps.
// The arguments are: v.create("yourVariableName", "Your Variable Contents");
v.create("myName", "Zougen Moriver"); // a simple String
v.create("primaryColours", ["red", "green", "blue"]); // an array of primary colours
v.create("someObject", {"greeting":"Hi There!"}); // A friendly object literal
// if you need to delete a variable again, this deletes the primaryColours array for example
v.destroy("primaryColours");
// 3. You can retreive any of the variables you create using v.get("variableName"). Here, we retreive the "name"...