Search code examples
javascriptkeyuponkeyup

Can't register keyup event in Javascript


I'm trying to implement a markdown editor similar to the one on Stackoverflow. I'm using SimpleMDE.

I have written the code below, but for some reason the 'keyup' event is not registering. Everything else works.

The key javascript part is here:

var input = document.getElementById('editable')
input.addEventListener('keyup', function(){
    console.log(simplemde.value())
    document.getElementById("content").innerHTML = simplemde.value()
})

The entire code looks like this:

var simplemde = new SimpleMDE({
  element: document.getElementById("editable")
})
simplemde.value("This text will appear in the editor")

var input = document.getElementById('editable')
input.addEventListener('keyup', function() {
  console.log(simplemde.value())
  document.getElementById("content").innerHTML = simplemde.value()
})
.editor {
  width: 45%;
  float: left;
}

.content {
  width: 45%;
  float: left;
}
<link rel="stylesheet" href="https://cdn.jsdelivr.net/simplemde/latest/simplemde.min.css">
<script src="https://cdn.jsdelivr.net/simplemde/latest/simplemde.min.js"></script>
<div class="editor">
  <textarea id="editable"></textarea>
</div>
<div class="content" id="content"></div>


Solution

  • The issue is because you've hooked your event handler to the original #editable element. This element is no longer in control of the content, it's all handled by the elements created by SimpleMDE to build its UI.

    To do what you require you should instead use the on() method of the codemirror property which SMDE exposes. A list of the available events is available from their documentation.

    var simplemde = new SimpleMDE({
      element: document.querySelector("#editable"),
      initialValue: "This text will appear in the editor"
    });
    
    simplemde.codemirror.on('keyup', function() {
      document.querySelector('#content').innerHTML = simplemde.value();
    })
    .editor {
      width: 45%;
      float: left;
    }
    
    .content {
      width: 45%;
      float: left;
    }
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/simplemde/latest/simplemde.min.css">
    <script src="https://cdn.jsdelivr.net/simplemde/latest/simplemde.min.js"></script>
    <div class="editor">
      <textarea id="editable"></textarea>
    </div>
    <div class="content" id="content"></div>

    Note, I'd suggest using the input or change events instead of keyup, as the latter doesn't fire if the user holds the key down, which can look odd.