LoginSignup
6
7

More than 5 years have passed since last update.

Bootstrap WYSIWYG Editorのsummrnoteで本文の文字数をカウント

Posted at

summrnoteで入力した本文の文字数をカウントできるようにするカスタマイズです。

Super Simple WYSIWYG Editor on Bootstrap
http://hackerwins.github.io/summernote/

A simple, Twitter style character counter for HTML input fields.
https://github.com/dtisgodsson/jquery-character-counter

イメージとして、以下で文字数を取得できれば便利なのですが

$("#body").val().length

実際にはHTML上に書き込まれていくため、
summrnote#code を使って以下のように文字数を取得します。

$('#body').code().length;

ということで、ここから具体的な話に移ります。

まずcharacter-counterの初期化をしましょう。myCounterで文字数のカウントを行います。

    $('#body').characterCounter({
      limit: 1024,
      myCounter: function() {
        return $('#body').code().length;
      }
    });

summernoteの初期化ではonkeyupとonpasteの発生する都度、文字数をカウントするよう指定します。

    $('#body').summernote({
      height: 300,
      lang: 'ja-JP',
      toolbar: [
        ['style', ['bold', 'italic', 'underline', 'clear']],
        ['fontsize', ['fontsize']],
        ['color', ['color']],
        ['para', ['ul', 'ol', 'paragraph']],
        ['height', ['height']],
        ['insert', ['picture', 'video']],
      ],
      onkeyup: function(e) {
        $('#body').trigger("summrnoteKeyup");
      },
      onpaste: function(e) {
        $('#body').trigger("summrnotePaste");
      },
    });

次にjquery.charactercounter.jsをちょっといじります。
defaultsにmyCounterを追加します。

        var defaults = {
            exceeded: false,
            counterSelector: false,
            limit: 150,
            counterWrapper: 'span',
            counterCssClass: 'text-primary',
            counterFormat: '%1',
            counterExceededCssClass: 'text-warning',
            onExceed: function(count) {},
            onDeceed: function(count) {},
            customFields: {},
            myCounter: null, // <-- ここ!
        }; 

文字数をカウントしている箇所を以下のようにmyCounterがあればそれを使うようにします。

        function checkCount(element)
        {
            var characterCount = (options.myCounter == null ? $(element).val().length : options.myCounter()) ;

イベントのバインドにsummrnoteKeyupとsummrnotePasteを追加してあげます。

     function bindEvents(element)
     {
         $(element)
             .bind("keyup", function () { 
                 checkCount(element); 
             })
             .bind("paste", function () { 
                 var self = this;
                 setTimeout(function () { checkCount(self); }, 0);
             })
             .bind("summrnoteKeyup", function () { 
                 checkCount(element); 
             })
             .bind("summrnotePaste", function () { 
                 var self = this;
                 setTimeout(function () { checkCount(self); }, 0);
             });
     }

以上で、summernoteで書きながら文字数がカウントされるようになります。

すっきり。

6
7
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
6
7