Created by dan on Tuesday 8th December, 2009 at 3:29 PM
Tags: Javascript, jQuery, Web development
OK, so this is a bit of a quick one, but I thought I best blog it so that I can refer back later on.
I have a DIV containing one or more paragraphs, which I want to be able to edit inline with TinyMCE. Seen as I'm using jQuery, I'd rather keep it that way, so I'm making use of the jQuery TinyMCE API.
I have a button, which is labelled 'Edit'. Upon clicking this, I want TinyMCE to take hold of the DIV, making it editable, inline. At the same time, I want the 'Edit' button to be relabelled 'Save'. I'm going to disregard the save action of TinyMCE for the time being, as I want to get the first bit out of the way.
Upon clicking 'Save', TinyMCE's content should be saved, and the instance should be destroyed. I never really found a solution to this, although it's much more simple than it seems. The below example does he first part very well, however the save function is not yet handled.
/* <![CDATA[ */
// Set selector of information box
var infoBoxID = 'information_box'
// Upon the DOM being ready
$(document).ready(function() {
$('input[type=button]#id_edit_information').click(function(e) {
// If editor is undefined
if (typeof($('div#'+infoBoxID).tinymce()) !== 'object') {
// Create an instance of TinyMCE
$('div#'+infoBoxID).tinymce({
theme_advanced_toolbar_location: 'top',
theme_advanced_toolbar_align: 'right',
theme_advanced_resizing: true,
theme: 'advanced',
theme_advanced_buttons1: 'save,|,bold,italic,underline,strikethrough',
theme_advanced_buttons2: '',
theme_advanced_buttons3: '',
theme_advanced_buttons4: '',
});
// Update button label
$(this).val('Save');
// If editor does exist
} else {
// TODO: Call save function first, then...
// Destroy TinyMCE instance
$('div#'+infoBoxID).tinymce().remove();
// Update button label
$(this).val('Edit');
}
// Prevent any further action from the button
e.preventDefault();
});
});
/* ]]> */
This works nicely in Safari and Firefox, although I've not tested it fully as yet, but I'm confident it'll work fine in the browsers we need to worry about. It also updates the content in place inside the DIV, so when destroyed, the content is left updated. Maybe this will help somebody else too...