Jump to content
dealtek

Newbie still learning about HTML5 and localStorage...

Recommended Posts

Hi All,I'm a bit confused as to how it all works - - sometimes I set the local localStorage like:localStorage.setItem("First", "Bob");localStorage.setItem("Last", "Smith");then read on another page like:<span id="First"></span> <span id="Last"></span><script>document.getElementById('First').innerHTML = localStorage.getItem("First");document.getElementById('Last').innerHTML = localStorage.getItem("Last");</script>sometimes it shows fine and sometimes on other pages some fields are blankand other page may show error like:Uncaught TypeError: Cannot set property 'innerHTML' of nullQ: What am I doing wrong - why was there sometimes errors?- if I use = document.getElementById('Last') - but fail to have the correct span id="xxxx" - does that cause the errors?- What is the criteria for getting this to always have fields show up?

Share this post


Link to post
Share on other sites

Try...

<script>window.onload = init;function init(){document.getElementById('First').innerHTML = localStorage.getItem("First");document.getElementById('Last').innerHTML = localStorage.getItem("Last");}</script>

Share this post


Link to post
Share on other sites

I agree that it probably is a timing issue though I would prefer the more modern approach of:

window.addEventListener('load', init,false);

You are getting the error because the script is sometimes firing before the HTML parser has completed creation of the elements and their nodes in the Document Object, so when the elements are referenced they do not yest exist and are therefore null, or undefined.

Share this post


Link to post
Share on other sites

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Paste as plain text instead

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

Loading...

×
×
  • Create New...