Search code examples
javascripthtmltitledata-uri

Dynamic title update from contenteditable


I'm making a little data URI for taking notes

data:text/html
<title>Text Editor</title>
<body>
  <div contenteditable class="text" id="title">Title...</div>
  <div contenteditable class="text">Body...</div>
</body>

https://jsfiddle.net/ab3hh3ka/

I'm wondering what kind of JavaScript could I use to dynamically update the title of the page as you write in the #title field. The goal is to be able to hit Ctrl+S to be to save the file with the title already in place.


Solution

  • For modern browsers, you can watch for the HTML5 input event for contenteditable elements like so (pure JS):

    document.getElementById("title").addEventListener("input", function(e) {
        var value = e.srcElement.innerHTML;
        document.title = value;
    }, false);
    

    https://jsfiddle.net/ab3hh3ka/3/