Search code examples
javascripthtmlgoogle-keep

How does the Google Keep text input work?


I'm looking into creating a text editor for my site and really liked how Google Keep does their text input. At first look based on the HTML, they don't appear use input fields / text areas but rather some sort of javascript mode of input that takes text input and generates the HTML equivalent that text and places it in the DOM. So is it likely that they built their own input functionality to allow them and the user to manipulate the content they put in? Or is it more likely that they have an all purpose input field or something that captures the data and it's just hidden from view?

This is all I see when I go looking into the DevTools

<div contenteditable="true" aria-multiline="true" role="textbox" class="notranslate IZ65Hb-YPqjbf h1U9Be-YPqjbf" tabindex="0" spellcheck="true" dir="ltr">
    This is their "input field"
    <br>
    That renders html 
    <br>
    Based on the text that's entered
    <br>
    But I want to know how I should be capturing this text
</div>

Solution

  • The contenteditable="true" and role="textbox" tell the DOM to treat the <div> element like a <textbox>. According to the WAI-ARIA Standards, this approach allows those with reading impairments to navigate the screen more easily, as a screen reader would have a better idea of what elements are on the page.

    Without seeing the rendered DOM, I can't be 100% sure what Google is doing, but it is very easy to manipulate the DOM based on user input as such. In the following example, I'm using targeting the input element, and then creating an onkeyup function that writes the content in a secondary 'output' <div>. This second <div> mirrors the input in the example, though can be coded to send the input to another page (or database) with AJAX, included elsewhere on the page, or styled to format the input in a nicer fashion.

    // Initial text
    document.getElementById('output').innerHTML = document.getElementsByClassName('h1U9Be-YPqjbf')[0].innerHTML
    
    // On change
    document.getElementsByClassName('h1U9Be-YPqjbf')[0].onkeyup = function() {
      document.getElementById('output').innerHTML = document.getElementsByClassName('h1U9Be-YPqjbf')[0].innerHTML
    }
    .h1U9Be-YPqjbf {
      border: 1px solid blue;
    }
    
    #output {
      margin-top: 20px;
      border: 1px solid red;
    }
    <div contenteditable="true" aria-multiline="true" role="textbox" class="notranslate IZ65Hb-YPqjbf h1U9Be-YPqjbf" tabindex="0" spellcheck="true" dir="ltr">
      This is their "input field"
      <br> That renders html
      <br> Based on the text that's entered
      <br> But I want to know how I should be capturing this text
    </div>
    
    <div id="output"></div>

    Hope this helps! :)