Skip to content

Instantly share code, notes, and snippets.

@mlconnor
Created June 26, 2014 18:39
Show Gist options
  • Save mlconnor/7e706d77ba51a6ef60fb to your computer and use it in GitHub Desktop.
Save mlconnor/7e706d77ba51a6ef60fb to your computer and use it in GitHub Desktop.
Spreadsheet Excel in 31 lines of code
<!DOCTYPE html>
<html>
<head>
<!-- fiddle is here http://jsfiddle.net/ondras/hYfN3 -->
<meta http-equiv="content-type" content="text/html; charset=UTF-8">
<title>Tiny Excel-like app in vanilla JS - jsFiddle demo by ondras</title>
<script type='text/javascript' src='/js/lib/dummy.js'></script>
<link rel="stylesheet" type="text/css" href="/css/result-light.css">
<style type='text/css'>
li {
list-style: none;
}
li:before {
content: "✓ ";
}
input {
border: none;
width: 80px;
font-size: 14px;
padding: 2px;
}
input:hover {
background-color: #eee;
}
input:focus {
background-color: #ccf;
}
input:not(:focus) {
text-align: right;
}
table {
border-collapse: collapse;
}
td {
border: 1px solid #999;
padding: 0;
}
tr:first-child td, td:first-child {
background-color: #ccc;
padding: 1px 3px;
font-weight: bold;
text-align: center;
}
footer {
font-size: 80%;
}
</style>
<script type='text/javascript'>//<![CDATA[
window.onload=function(){
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) {} });
})();
}//]]>
</script>
</head>
<body>
<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>&copy; 2013 <a href="http://ondras.zarovi.cz/">Ondřej Žára</a></p></footer>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment