WordPress uses TinyMCE for its visual editor, making in hard to use regular JavaScript for custom situations. Luckily, TinyMCE provides some callbacks that we can use.
In this example, I’ll show how you can do something when content of visual editor in WordPress has been accessed or changed by using TinyMCE’s handle_event_callback
callback.
To register this callback, you need to use WordPress teeny_mce_before_init
filter. This filter is used to filter TinyMCE’s options list before initialization. In this case, it would look like:
/**
* Register callback on TinyMCE focus
*/
function md_callback_on_tinymce_click( $mceInit ) {
$mceInit['handle_event_callback'] = "mdCallbackFunction";
return $mceInit;
}
mdCallbackFunction
is just a normal JavaScript function that accepts parameter event
and that you can place anywhere in you custom JavaScript code. In this case, it would look like:
function mdCallbackFunction(e) {
// Do something
}
Here is one real world situation where this trick can be used. Code below will hide Submit button on bbPress forms and it will show it only when you click on a text editor, either visual or text.
/**
* Add bbPress TinyMCE focus callback function.
*/
function md_bbp_show_submit_on_tinymce_click( $mceInit ) {
$mceInit['handle_event_callback'] = "mdShowBbpSubmit";
return $mceInit;
}
/**
* Display submit button on bbPress TinyMCE focus.
*/
function md_register_bbp_submit_onclick() {
add_filter( 'teeny_mce_before_init', 'md_bbp_show_submit_on_tinymce_click' );
?>
<script type="text/javascript">
jQuery(document).ready(function($){
// Hide Submit button
$('#bbp_topic_submit').hide();
$('#bbp_reply_submit').hide();
// Display button when clicked in Text mode
$("#bbp_topic_content").live('focusin', function (data) {
$('#bbp_topic_submit').show();
});
$("#bbp_reply_content").live('focusin', function (data) {
$('#bbp_reply_submit').show();
});
});
function mdShowBbpSubmit(e) {
jQuery('#bbp_reply_submit').show();
jQuery('#bbp_topic_submit').show();
}
</script>
<?php
}
add_action( 'bbp_theme_before_reply_form', 'md_register_bbp_submit_onclick' );
add_action( 'bbp_theme_before_topic_form', 'md_register_bbp_submit_onclick' );