Created
November 14, 2013 06:30
-
-
Save arkiver/7462377 to your computer and use it in GitHub Desktop.
Spreadsheet program in under 30 lines of JavaScript
This file contains 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
//Written by: http://ondras.zarovi.cz/ | |
//http://jsfiddle.net/ondras/hYfN3/ | |
// <p>Inspired by <a href="http://thomasstreet.net/blog/spreadsheet.html">http://thomasstreet.net/blog/spreadsheet.html</a>. Features:</p> | |
// <ul> | |
// <li>Under 30 lines of vanilla JavaScript</li> | |
// <li>Libraries used: <strong>none</strong></li> | |
// <li>Excel-like syntax (formulas start with "=")</li> | |
// <li>Support for arbitrary expressions (=A1+B2*C3)</li> | |
// <li>Circular reference prevention</li> | |
// <li>Automatic localStorage persistence</li> | |
// </ul> | |
// <table></table> | |
// <footer><p>© 2013 <a href="http://ondras.zarovi.cz/">Ondřej Žára</a></p></footer> | |
for (var i=0; i<6; i++) { | |
var row = document.querySelector("table").insertRow(-1); | |
for (var j=0; j<6; j++) { | |
var letter = String.fromCharCode("A".charCodeAt(0)+j-1); | |
row.insertCell(-1).innerHTML = i&&j ? "<input id='"+ letter+i +"'/>" : i||letter; | |
} | |
} | |
var DATA={}, INPUTS=[].slice.call(document.querySelectorAll("input")); | |
INPUTS.forEach(function(elm) { | |
elm.onfocus = function(e) { | |
e.target.value = localStorage[e.target.id] || ""; | |
}; | |
elm.onblur = function(e) { | |
localStorage[e.target.id] = e.target.value; | |
computeAll(); | |
}; | |
var getter = function() { | |
var value = localStorage[elm.id] || ""; | |
if (value.charAt(0) == "=") { | |
with (DATA) return eval(value.substring(1)); | |
} else { return isNaN(parseFloat(value)) ? value : parseFloat(value); } | |
}; | |
Object.defineProperty(DATA, elm.id, {get:getter}); | |
Object.defineProperty(DATA, elm.id.toLowerCase(), {get:getter}); | |
}); | |
(window.computeAll = function() { | |
INPUTS.forEach(function(elm) { try { elm.value = DATA[elm.id]; } catch(e) {} }); | |
})(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment