Home>

As the title suggests, I have created a WYSIWYG editor and I want to make it bold when I press the bold button, but it doesn't work.

https://codepen.io/Shokeen/pen/pgryyN ? editors = 1010

I want to make the text bold when I press the B button, as in the link above.

Error situation

When I checked with console, there was no error.

Code

# index.html
<html>
<head>
  <title>WYSIWYG practice</title>
  <meta http-equiv = "content-type" charset = "utf-8">
  <script type = "text/javascript" src = "wysiwyg.js"></script>
</head>
<body>
  <div>
    <a href = "#" data-command = "bold">B</a>
    <div contenteditable>
      <p>This is WYSIWYG</p>
    </div>
  </div>
</body>
</html>
# wysiwyg.js
function startWYSIWYG () {
  function wysiwygGet (element) {
    let command = element.getAttribute ('data-command');
    document.execCommand (command, false, null);
   };
  let editorTags = document.querySelectorAll ('# toolbar a');
  for (let i = 0;i<editorTags.length;i ++) {
    editorTags [i] .addEventListener ('click', wysiwygGet, false);
  };
};
 document.addEventListener ('load', startWYSIWYG, false);
  • Answer # 1

    I was able to resolve myself.

    function startWYSIWYG () {
    let editorTags = document.querySelectorAll ('# toolbar a');
    for (let i = 0;i<editorTags.length;i ++) {
    editorTags [i] .addEventListener ('click', wysiwygGet, false);
    };
    };
    function wysiwygGet () {
      let command = this.getAttribute ('data-command');
      document.execCommand (command, false, null);
    };
    window.addEventListener ('load', startWYSIWYG, false);

    The corrected part is

    -Replaced wysiwygGet function with let command = this.getAttribute ('data-command') ;.

    ・ Modify to window.addEventListener ('load', startWYSIWYG, false);instead of document