Sunday, September 7, 2008

FCKEditor 2.x: How to add a new button with custom javascript to the toolbar

In this tutorial we will have a look at how to add a new button with custom javascript to a FCKeditor toolbar. In this example our custom button will simply open a link in a new window when it's clicked.

1. Start by finding the "plugins" folder which is located below the "fckeditor\editor" folder.
2. Create a new folder, name it "openurl".
3. Add an icon within the "openurl" folder, name it "openurl.gif".
4. Create a new file within the "openurl" folder, name it "fckplugin.js", and add the following code:


// Our method which is called during initialization of the toolbar.
function OpenUrl()
{
}

// Disable button toggling.
OpenUrl.prototype.GetState = function()
{
 return FCK_TRISTATE_OFF;
}

// Our method which is called on button click.
OpenUrl.prototype.Execute = function()
{
 window.open('http://www.kindblad.com');
}

// Register the command.
FCKCommands.RegisterCommand('openurl', new OpenUrl());

// Add the button.
var item = new FCKToolbarButton('openurl', 'Open URL');
item.IconPath = FCKPlugins.Items['openurl'].Path + 'openurl.gif';
FCKToolbarItems.RegisterItem('openurl', item);

5. Now we need to define where we want our button to be shown in the toolbar. Open up "fckeditor\fckconfig.js" and look for:


FCKConfig.ToolbarSets["Default"] = [
 ['Source'],
 ['Cut','Copy','Paste','PasteText','PasteWord','-','SpellCheck'], 
 ...

Add 'openurl' anywhere in the toolbar definition, e.g.:


FCKConfig.ToolbarSets["Default"] = [
 ['openurl,'Source'],
 ['Cut','Copy','Paste','PasteText','PasteWord','-','SpellCheck'], 
 ...

6. And lastly, we need to tell FCKeditor to load our plugin, we do this by finding the following string in the "fckeditor/fckconfig.js".

FCKConfig.PluginsPath = FCKConfig.BasePath + 'plugins/' ;

Add the following code below the line above:

FCKConfig.Plugins.Add('openurl');

That's it.