TinyMCE checkbox toggler for jQuery
Here’s a small jQuery code snippet that you can use to have an easy to use checkbox toggler to enable or disable a TinyMCE editor with ease (tested on TinyMCE version 4 and jQuery version 2.1.1).
It’s really easy to use. You just need to create a checkbox element with the class tiny_mce_toggler and a data attribute with the key editor and the text area id used as a TinyMCE editor as a value. The snippet can be easily extracted if you want to use it differently.
Here is the javascript snippet:
$(function() {
var TinyMceToggler = function(_checkbox){
var checkbox = $(_checkbox);
var editor = checkbox.data('editor');
checkbox.click(function(){
if (this.checked) {
console.log("Add");
tinyMCE.execCommand( 'mceAddEditor', false, editor );
}
else {
console.log("Remove");
tinyMCE.execCommand( 'mceRemoveEditor', false, editor );
}
});
};
$("input.tiny_mce_toggler").each(function(){
new TinyMceToggler(this);
});
});
And here you can see how to integrate it on a page with a TinyMCE editor:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>TinyMCE - Toggler</title>
<link type="text/css" rel="stylesheet" href="http://moxiecode.cachefly.net/tinymce/v8/css/all.min.css?v=8" />
<script src="//ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script type="text/javascript" src="javascript/tinymce/tinymce.min.js"></script>
<script type="text/javascript">
$(function() {
tinymce.init({
selector: "textarea"
});
var TinyMceToggler = function(_checkbox){
var checkbox = $(_checkbox);
var editor = checkbox.data('editor');
checkbox.click(function(){
if (this.checked) {
console.log("Add");
tinyMCE.execCommand( 'mceAddEditor', false, editor );
}
else {
console.log("Remove");
tinyMCE.execCommand( 'mceRemoveEditor', false, editor );
}
});
};
$("input.tiny_mce_toggler").each(function(){
new TinyMceToggler(this);
});
});
</script>
</head>
<body>
<form method="post" action="#">
<input type="checkbox" data-editor="tiny" checked="checked" class="tiny_mce_toggler" style="display: block;" />
<textarea id="tiny"></textarea>
</form>
</body>
</html>
You can run the example on this fiddle: http://fiddle.tinymce.com/7jeaab