I am using markItUp for a textarea in a WP widget (that is, on widgets.php page, while creating and editing a widget).
The textarea is markItUp'ed when I first open the widget, but after I click save the functionality is lost and I am back to a regular textarea.
I compared the source code for the before-save and after-save versions of the page and there is no difference -obviously, as the page isn't reloaded. Does jQuery need to be invoked for every ajax call?
I tried adding
jQuery(".markitup").markItUp(mySettings);
inside the widget's form handling function but that didn't help. I tried to make changes binding this event to the save button too but that didn't seem to make a difference (there is a good chance that I got it all wrong).
The jQuery
So, the first thing you need to do is hook into the AJAX call so you are notified when the widgets have been saved. To do this, we will use the jQuery ajaxSuccess
function. Put this in its own js
file:
// Use a self executing function so we can safely use
// $ inside and know it = jQuery
(function($){
// Tie into all jQuery AJAX requests
$(document).ajaxSuccess(function(e, x, o){
// Make sure our widget is the one being saved
// id_base will equal whatever is set in the PHP for the widget
// In this example, we target the text widget
if(o.data && o.data.indexOf('id_base=text') > -1){
// Now, lets quickly find all the right elements
// and filter out the ones already set up, and finally
// apply the `markItUp` call, but we will delay just to give
// WP a chance to update the widget
window.setTimeout( function(){
$("textareas.markItUp:not(.markItUpEditor)").markItUp(mySettings);
}, 200 );
}
});
})(jQuery);
The PHP/WordPress
Finally, tell WP to include your new js file only on the widgets page. You will need to incorporate this either into functions.php
or if you are building a widget, into the widgets PHP file:
function register_markitup(){
wp_enqueue_script( 'markitup-widgets', WP_PLUGIN_URL . '/your-plugin/js/markitup-ajax.js' );
}
add_action( "admin_print_scripts-widgets.php", 'register_markitup' );
Edit I had an incorrect add_action
hook when I posted. It needed the .php
which I just added. The code is correct now.