skip to Main Content

Complete javascript beginner here.

I’m trying to make it so my text document saves its content in my textbox whenever I refresh the page, but for some reason whenever I try to see if the content’s been saved the value just comes back as null.

Here’s my HTML

div class="scratchpad" contenteditable="true" name="scratchpad" id="scratchpad"></div>

and here’s my javascript

let scratchpad = document.querySelector("#scratchpad")

scratchpad.value = localStorage.getItem("notes")

scratchpad.addEventListener("keyup", event => {
    localStorage.setItem("notes", scratchpad.value)
})

I’m using Visual Studio Code in Windows 11

The only thing I can think of is it might have something to do with using contenteditable instead of a textarea but I’m not sure how that would effect the localstorage value.

Any help would be appreciated. And feel free to talk to me like I’m five years old because part of me still can’t wrap my head around some of this stuff.

2

Answers


  1. You’re setting the value property, but that only exists on form input elements like textareas. Instead, try setting the innerText property:

    scratchpad.innerText = localStorage.getItem("notes")
    
    Login or Signup to reply.
  2. You’re trying to use scratchpad.value instead of scratchpad.innerHTML, but value is not a property of a div element. Instead, use innerHTML to get and set the content of a div element with contenteditable attribute.

    Here’s an updated version of your code:

    document.addEventListener("DOMContentLoaded", (event) => {
      let scratchpad = document.querySelector("#scratchpad");
    
      scratchpad.innerHTML = localStorage.getItem("notes");
    
      scratchpad.addEventListener("input", (event) => {
        localStorage.setItem("notes", scratchpad.innerHTML);
      });
    });
    

    Note that I changed the event listener to "input" instead of "keyup". This will listen for any changes made to the div element, regardless of whether the user is using the keyboard or another input device.

    You also need to run code after the #scratchpad element has been loaded in the DOM. You can do this by wrapping your code in a DOMContentLoaded event listener.

    I tried the above code in Chrom and it works fine.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search