Search code examples
htmlcontenteditable

Make part of a paragraph editable


I am making an interactive poem where I have blank spaces that can be filled in with the right word. Can anyone advise me on how to make just these spaces editable and not the rest of the poem?

Here is the poem:

<pre id="poem">
<b><u>Social Media</b></u>

Relax yourself,
As I ______
through your mind
Scroll down the pages
of your spine
Reading every word 
and thought on
your ____ like a ____
Stumbled Upon 
you then _______ onto
your looks--IGuess
I'm ______ into you
You're my one
and only ________

Will you ______ me?

</pre>

Solution

  • You can surround the editable areas with a <span> element which is contenteditable:

    function isValid()
    {
      if (document.getElementById('poem-word1').innerText == 'test') {
        alert("valid");
      } else {
        alert("not valid");
      }
    }
    <pre id="poem">
    <b><u>Social Media</b></u>
    Relax yourself,
    As I <span contenteditable id="poem-word1">______</span>
    through your mind
    Scroll down the pages
    of your spine
    Reading every word 
    and thought on
    your <span contenteditable>____</span> like a <span contenteditable>____</span>
    Stumbled Upon 
    you then <span contenteditable>_______</span> onto
    your looks--IGuess
    I'm <span contenteditable>______</span> into you
    You're my one
    and only <span contenteditable>________</span>
    
    Will you <span contenteditable>______</span> me?
    </pre>
    <button onclick="isValid()">Validate</button>

    Note: If you need to submit these values you should use a <form> with <input> elements.