LoginSignup
9
10

More than 5 years have passed since last update.

クリックしてHTMLを編集できる<textarea>に切り替えるjQuery

Posted at

概要

クリックしたらHTMLを編集できるになる、つまり、

before.png

これが

after.png

こうなるやつです。

コード例

上の画像のコードは下記の通りです。

index.html
<!DOCTYPE html>
<html>
<head>
  <title>sample</title>
  <meta charset="utf-8">
  <style type="text/css">
  .wrapper {
    width:400px;
    padding: 100px;
    text-align: center;
    background-color: #a2edde;
  }
  .click-me textarea {
    width: 100%;
    height: 100%;
    min-height: 3em;
    padding: 0;
  }
  </style>
</head>
<body>

  <h1>Click to Textarea</h1>
  <div class="wrapper">
    <p class="click-me">
      This <strong>text</strong> is <i>clickable</i>, so <a href="#">click me</a>!
    </p>
  </div>

  <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
  <script>

  $(function() {

    $('.click-me').on('click', function() {
      var $editable = $(this);

      $editable.html('<textarea>' + $editable.html() + '</textarea>').find('textarea')
        .focus() // これが必要
        .on('focusout', function() {
            var valueOfTextarea = $(this).val();
          $editable.html( valueOfTextarea );
        })
        .on('click', function(ev) {
            // p.click-me のクリックイベントの発火を防止
          ev.stopPropagation();
        });
    });

  });

  </script>
</body>
</html>

デフォルトでは textarea の幅が非常に狭くなるのでCSSで設定しています。

ハマりどころとしては、

  • <textarea>を作った直後、focus()しないと最初のfocusoutが発火しない
  • stopPropagation()しないと.click-meのイベントが再度発火する

といったところでしょうか。
(個人的にはjQueryのセレクタの扱いでもハマりましたが。。)

9
10
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
9
10