Search code examples
javascripthtmlcssfrontendcontenteditable

How To Detect If Content Of contenteditable div Was Changed


I am trying to figure out if it's possible to detect a contenteditable div with content as text when the client changes the text. I am trying to design a simple profile page where the user can click the div, edit it and when they are done editing it the contents of that div get stored as a Javascript variable to be sent to my API. I am fairly new to webdevelopment, and I will appreciate it if someone enlightens me on how this can be done in Javascript.

relevant code:

   <div class="bio1" contenteditable="true" name="bio" id="bio">
   Apparently, this user prefers to keep an air of mystery about them.
   <br>
   <br>
   <hr class="hrStyle">

The tags do close, but after many other divs.

what I tried:

  1. I searched stack overflow for similar questions but did not find one Javascript specific
  2. I thought of using a button that when they click a div, the button appears and gets the content of that div once clicked. I was discouraged by this because I wasn't sure how to detect the div click in the first place, and I wanted to see if there was a none button solution.

Solution

  • You can use the "input" event to listen for all changes by made by keyboard or paste.

    As for being done, that would probably require some button in order for user to indicate they have finished, or use a timer to compare a stored value to current value to check if changes have been made

    document.getElementById('bio').addEventListener('input', function(){
       console.clear()
       console.log(this.innerHTML)
    })
    <div class="bio1" contenteditable="true" name="bio" id="bio">
      Apparently, this user prefers to keep an air of mystery about them.
      <br>
      <br>
      <hr class="hrStyle">
    </div>