LoginSignup
1
1

More than 5 years have passed since last update.

Tinymce初期化後にボタンを有効化・無効化する

Posted at

はじめに

Tinymce(バージョン4)初期化後に外部からの操作でボタンの有効・無効切り替えしようと思ったのだけど、なかなか方法が見当たらなかった。
StackOverflowで検索しまくって、なかなか検索ワードが見つからない感じ。
最終的に役に立ったのがこの記事の後半だった。
http://www.devsumo.com/technotes/2014/08/tinymce-4-enabling-and-disabling-toolbar-buttons/

サンプル

上記を参考にサンプルを書いた。

test.html
<!DOCTYPE html>
<html>
<head>
  <script src="https://cloud.tinymce.com/stable/tinymce.min.js"></script>
  <script src="https://code.jquery.com/jquery-1.12.4.min.js"></script>
  <script>

  var myBtn=null;
  tinymce.init({ 
  selector:'textarea' 
  ,toolbar:"strikeout"
  ,init_instance_callback  : initEditor
  , setup: function(editor) {
    editor.addButton('strikeout', {
      icon: 'strikethrough',
      onclick: function() {
        editor.execCommand('mceToggleFormat', false, 'strikethrough');
      },
      onpostrender: function() {
        // toolbarのstrikeoutボタンを変数にセット
        myBtn = this;
      }
    });

    // 外部ボタンが押されたときに実行するメソッド
    editor.on('act1',function(){
      if(myBtn) {
        myBtn.disabled(true);
      }
    })
  }

  });

  // エディタの初期化時に実行するメソッド
  function initEditor(inst) {
    // 外部ボタンのonclickイベントを登録
    $('#btn').on('click',function(){
      tinymce.activeEditor.fire('act1');
    });
  }

  </script>
</head>
<body>
  <textarea>editor</textarea>
  <button id="btn">btn</button>
</body>
</html>

このサンプルでは、「btn」を押すと「act1」メソッドを実行させている。act1のなかでbutton.disabled()を書く。
*disabledの引数で、有効無効切り替えできる。

説明など

Tinymceのボタンのドキュメントはここにある。
https://www.tinymce.com/docs/api/tinymce.ui/tinymce.ui.button/
「hide」というメソッドもあって、これを使うとボタンを隠せる。

tinyMCE.activeEditorでEditorオブジェクトを取れるんだけど、そこからselectButton()みたいなメソッドないのかとか調べた。それは無くて、方法としては
setup -> onPostRender時にボタンオブジェクトをJavascriptの変数にセットする
というやり方になる。

StackOverflowとか見てると、tinyMCE.activeEditorがnullなんだけど?の質問にtinyMCE.get('id')で取れるよ、みたいな回答とかあって、
そうじゃなくてinit_instance_callback を使うとactiveEditorが取れるということがわかった。
ドキュメントが英語なのとカスタマイズしたコードのサンプルが少ないので、何か使い方がよくわからんと思ってしまっていた。

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