0

Why doesn't this work? localStorage.fontSize contains the proper value, but the first document.body.style.fontSize = localStorage.fontSize + "pt"; doesn't update the style.

<script type="text/javascript">

if(!localStorage.fontSize){
    localStorage.fontSize = Number(11); 
}
else{
    document.body.style.fontSize = localStorage.fontSize + "pt"; /* This row doesnt run */
}

function resetFont(){
    localStorage.fontSize = Number(11);
    document.body.style.fontSize = "11pt";
}
function enlargeFont(){
    localStorage.fontSize++;
    document.body.style.fontSize = localStorage.fontSize + "pt"; /* But this does if called */
}

</script>

No jQuery snippets please.

Alexey Gorozhanov
  • 616
  • 10
  • 20
  • 7
    Seems like `document.body` does not exist at the moment the code is run. Move the code to the end of the `body` tag. See http://stackoverflow.com/q/14028959/218196, it's basically the same. – Felix Kling Jun 03 '13 at 22:35
  • Try placing your script tag just before the end of the body tag – Sushanth -- Jun 03 '13 at 22:35
  • Did you look at the console? Open it up! – epascarello Jun 03 '13 at 22:38
  • Thank you Felix, case closed! – user1677709 Jun 03 '13 at 22:38
  • Shouldn't this code be at the *beginning* of the `` tag instead of the end? If it's at the end you could have a flash of unstyled content where the font size changes after the page has been displayed. – Michael Geary Jun 03 '13 at 22:45
  • @FelixKling, please create an answer for your answer, so that user1677709 can mark that as the correct answer. That way, no one wastes their time on answering a question that has already been answered. – myfunkyside Apr 29 '15 at 22:34
  • @myfunkyside: This question is two years old, but ok. – Felix Kling Apr 29 '15 at 22:36
  • @FelixKling - Ha, didn't even notice that:D But it does illustrate my point: I was just browsing on the main page for unanswered questions, and this one appeared in that list, because officially it still didn't have an answer – myfunkyside Apr 29 '15 at 22:40
  • @myfunkyside: Point taken! Though I'm not very hopeful that the answer will get accepted... – Felix Kling Apr 29 '15 at 22:42

1 Answers1

0

Seems like document.body does not exist at the moment the code is run. Move the code to the beginning or the end of the body tag.

See Why does jQuery or a DOM method such as getElementById not find the element?, it's basically the same.

Community
  • 1
  • 1
Felix Kling
  • 705,106
  • 160
  • 1,004
  • 1,072