To learn JavaScript I am writing a small text editor Google Chrome extension. But I keep getting this error: Cannot read property 'value' of undefined. It happens whenever tranquility.save(); is called, but not when tranquility.open(); which is weird because they are basically the same, just switched the sides. paper is just a <textarea>.
var tranquility = {
paper: document.getElementById("paper"),
lastOpenedPaper: localStorage.getItem("lastOpenedPaper"),
listen: function() {
this.paper.addEventListener("keyup", this.save, false);
},
save: function() {
localStorage.setItem(this.lastOpenedPaper, this.paper.value);
},
open: function() {
this.paper.value = localStorage.getItem(this.lastOpenedPaper);
}
}
EDIT:
It is called after <textarea> is created (unless it has to be the entire DOM)
<body>
<textarea id="paper"></textarea>
<script src="../js/application.js"></script>
<script>
tranquility.listen();
</script>
</body>
I got it working with two fixes
1.) Write the script after loading of paper textarea. It was done by placing script at the end of body.
2.) I found
localStorage.setItemandlocalStorage.getItemshould refer to the variable name like in http://hacks.mozilla.org/2009/06/localstorage/ . In your code lastOpenedPaper would refer to null value in begining so it won’t store value in that name so i tried replacing it with just. you can use other var name too or use varname directly aslocalStorage.setItem('anyvarname', this.paper.value);code: