jHtmlArea – Adding Custom Toolbar Buttons

18. August 2009

I’ve gotten a couple questions lately about extending the jHtmlArea WYSIWYG editor, so I thought I’d post a little bit about how to add your own custom toolbar buttons to it. There is one example that is included with the component, but that doesn’t cover inserting some html into the editor, so I’m going to cover that here.

You can download the jHtmlArea Editor here: http://jhtmlarea.codeplex.com/Release/ProjectReleases.aspx

This article was written with jHtmlArea v0.6.0 in mind, but it will work with newer releases.

Add a simple Custom Toolbar Button

As the jHtmlArea samples show you can specify your own list of toolbar buttons to display at the time of initializing the editor. You do this by passing in the “toolbar” option with an array of toolbar button groups (“Arrays”) that include the toolbar buttons. The editor has a bunch of buttons built in and those are specified by name. But, to add a custom toolbar button, you just need to pass in a simple JavaScript object that defines the button.

Here’s an example object literal that can be used to create the custom toolbar button:

{
    css: "custombutton", // The CSS class used to Style the <A> tag of the Toolbar Button
    test: "Custom Button Tooltip", // The text to use as the <A> tags "Alt" attribute, or tooltip
    action: function(btn) { // The function to execute when the Toolbar Button is Clicked
        // 'this' = jHtmlArea Object
        // 'btn' = jQuery object that represents the <A> "anchor" tag for the Toolbar Button

        // Take some action or Do Something Here
    }
}

 

As you can see it’s really pretty straight forward to define a custom toolbar button. Now to include the Custom Toolbar Button, you can send it in the “toolbar” option with all the other buttons you want displayed. Here’s an example that specifies a few of the built in toolbar buttons along with a new Custom Toolbar Button:

$("textarea").htmlarea({
    // Override/Specify the Toolbar buttons to show
    toolbar: [
        ["html"], ["bold", "italic", "underline", "|", "forecolor"],
        ["h1", "h2", "h3", "h4", "h5", "h6"],
        ["link", "unlink", "|", "image"],
        [{
            // This is how to add a completely custom Toolbar Button
            css: "datebutton",
            text: "Today's Date",
            action: function(btn) {
                // 'this' = jHtmlArea object
                // 'btn' = jQuery object that represents the <A> "anchor" tag for the Toolbar Button

                // Take some action or Do Something Here
            }
        }]
    ]
});

 

A couple things to note when specifying the custom set of Toolbar Buttons to display:

  • A Custom Toolbar Button is specified by passing in a JavaScript Object that has the “css”, “text” and “action” properties set accordingly. As shown above.
  • The “toolbar” option accespts an Array of Arrays. This allows for you to specify as many Toolbar Button Groups as you want. These Toolbar Button Groups will auto-wrap to the next line if they cannot all be displayed on the same line because of the width of the editor being too small. If you include ALL your buttons in a single group, then they will not wrap.
  • You can specify the “built in” Toolbar Buttons by “name”. To look what the names are, just reference the “jHtmlArea.defaultOptions” objects “toolbar” property as this is a full list of all the “built in” buttons.
  • To specify a “Separator” or vertical line to display in between the buttons within the same group, just specify a vertical pipe (“|”) character as the “name” of the toolbar button to display, and the editor will take care of the rest.
    Also do not forget to specify the CSS class you are telling the editor to use for the Custom Toolbar Button. You can see an example of this with the Custom “Save” Toolbar Button that is contained within the “default.htm” file that comes with the jHtmlArea editor download zip file.

Performing Basic Actions from a Custom Toolbar Button

Something that was omitted from the above example was how to actually perform some action on the editor. You can actually call any of the jHtmlArea objects methods from within the Custom Toolbar Buttons “action” method to perform some kind of manpulation or action on the editor. The jHtmlArea editor object is passed to the “action” method as the “this” keyword so it can be accessed directly without needing to curry any variables.

Here are some of the methods that you can call with a note as to what they do. You can find more within the jHtmlArea’s script file, or with documentation comments within the “-vsdoc.js” file.

{
    css: "custombutton",
    text: "Custom Toolbar Button",
    action: function(btn) {

        // Paste some specific HTML / Text value into the Editor
        this.pasteHTML("<p></p>");

        // Get the currently selected HTML / Text within the Editor
        var s = this.getSelectedHTML();

        // Set the current selection to Bold
        this.bold();

        // Set the current selection to Italic
        this.italic();

        // Set the current selection to Underline
        this.underline();

        // Center Justify the current selection
        this.justifyCenter();

        // Indent the current selection
        this.indent();

        // Insert horizontal rule or <hr> tag
        this.insertHorizontalRule();

        // Insert an Image by URL
        this.image("http://domain/image.png");

        // Set the Forecolor / Text Color of the current selection
        this.forecolor("#336699");

        // Get the Full HTML that's contained within the Editor
        var html = this.toHtmlString();
    }
}

 

One thing to note about using “pasteHTML” to insert your own custom HTML string into the editor, is because of the way the browsers handle comment tag (“<!-- -->”) they wont pasted/inserted and no exceptions will be raised. The reason I mention this is because I got a question from someone about inserting “<!—more—>” into the Editor.

Also the “btn” argument that’s passed to the “action” method is a reference to the jQuery object for the <A> “anchor” tag that is contained within the Custom Toolbar Button. This allows you to modify it’s CSS styles or absolute position an element near it, similarly to how the “jHtmlArea.ColorPickerMenu” extension does.

Append the Custom Toolbar Button to the “Default” Toolbar Button Set

You can append any Custom Toolbar Buttons you want to the “Default” Toolbar Button Set if you wish for those Custom Toolbar Buttons to be shown on ALL jHtmlArea editors on the Page. To do this you can just append a new Toolbar Button Group to the “jHtmlArea.defaultOptions.toolbar” array. However, make sure you do this before initializing an instance of jHtmlArea, otherwise the button will not be displayed.

Here’s an example that demonstrates appending a Custom Toolbar Button that  pasted the current days date into the editor when clicked:

jHtmlArea.defaultOptions.toolbar.push([
    {
        // This is how to add a completely custom Toolbar Button
        css: "datebutton",
        text: "Today's Date",
        action: function(btn) {
            // 'this' = jHtmlArea object
            // 'btn' = jQuery object that represents the <A> "anchor" tag for the Toolbar Button

            var m_names = new Array("January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December");

            var d = new Date();
            var curr_date = d.getDate();
            var curr_month = d.getMonth();
            var curr_year = d.getFullYear();
            this.pasteHTML(m_names[curr_month] + " " + curr_date + ", " + curr_year);
        }
    }
]);

jquery, JavaScript , ,

JavaScript: Easily "Extend" an Object/Element

29. July 2009

If you use jQuery then you may be familiar with its "jQuery.extend" method. The "jQuery.extend" method allows you to easily extend one object with one or more others. This is something that can really come in handy, especially when dealing with passing in "options" to a method, and needing to have them "default" to certain values.

For Example:

// "Default" to showing both Toolbar and Footer
var defaultOptions = { showToolbar: true, showFooter: true };

function MyObject = function(options){
    // Create a new "opts" variable that is a copy of "defaultOptions", then apply all values from "options"
    var opts = jQuery.extend({}, defaultOptions, options);

    // Now you have the "opts" variable that has all the "defaultOptions" values merged with the
    // "options" that were passed in to the function.

    // Do Stuff According to "opts" defined

}
MyObject.prototype = {};

// Example of creating new MyObject and passing it only the values you want to override the defaults
var obj = new MyObject({ showFooter: false });
// The above line will tell the new "MyObject" to show the toolbar, but not the footer.

Why use this?

As you can probably tell from the above example of doing this with jQuery, this really helps to simplify and reduce the amount of code you write. The benefits are smaller .js files for the browser to download, and it's just easier to read/maintain the code.

If you still have questions about this, then the following non-jQuery example of doing the same thing should help clear things up for you.

What if I'm Not using jQuery?

As you can probably see, the above example can really help to keep things simple. However, if you're not using jQuery how would you do this?

Now the "jQuery.extend" method has some logic to make sure the resulting object is only a copy and doesn't contain any references to the original so you don't mess things up, but below is really simplified version that will get the job done in most cases.

// Create Global "extend" method
var extend = function(obj, extObj) {
    if (arguments.length > 2) {
        for (var a = 1; a < arguments.length; a++) {
            extend(obj, arguments[a]);
        }
    } else {
        for (var i in extObj) {
            obj[i] = extObj[i];
        }
    }
    return obj;
};

Here's some examples of using the above "extend" method:

var Person = function() {
};
Person.prototype = {
    FirstName: null,
    LastName: null
};       

var person1 = new Person();
// Set multiple object properties with a single line of code
extend(person1, { FirstName: "John", LastName: "Doe" });
alert(person1.FirstName + " " + person1.LastName);

// Create a new Person instance and set it's properties in 1 line
var person2 = extend(new Person(), { FirstName: "John", LastName: "Doe" });
alert(person2.FirstName);

// "clone" person2
var person3 = extend(new Person(), person2);
alert(person3.LastName);

// "clone" person2 and add new properties
var person4 = extend(new Person(), person2, { Age: 18 });
alert(person4.FirstName + " :: " + person4.Age);

This can also be used to more easily add new HTML Elements to a page:


var js = extend(document.createElement("script"), { type: "text/javascript", src: "test.js" });
document.body.appendChild(js);

//As you can see the above is simpler than the traditional method of creating a new <script> Element
var js = document.createElement("script");
js.type = "text/javascript";
js.src = "test.js";
document.body.appendChild(js);

Conclusion

Now the use of the above method is actually really simple, and the end result is pretty much identical to the "jQuery.extend" method for simple tasks. If you want to have a cleaner "cloning" of the object values that get merged, then you'll probably want to use the "jQuery.extend" method or just copy it into your project if you aren't using jQuery.

Enjoy.

JavaScript, jquery ,

jHtmlArea 0.6.0 Update with Improved Functionality

24. July 2009

I just posted a pretty good update the the jHtmlArea project that includes quite a few more toolbar buttons and a new Color Picker Menu extension/plugin (jHtmlAreaColorPickerMenu) that adds a nice, simple color picker when using the "forecolor" toolbar button.

jHtmlArea is a simple, light weight, extensible WYSIWYG HTML Editor built on top of jQuery. This component allows you to easily display a WYSIWYG HTML Editor in place of any TextArea DOM Elements on the page. The minified script alone is 8.7kb, and with css and image files it's a total of 22k.

Download: jHtmlArea Project Home

To the right is an updated screenshot of the latest release, plus below is a full change log for this update release:

- Hide All Toolbar buttons except the "html" button when entering
HTML Source view (via clicking "html" button or executing
jHtmlArea.showHTMLView). When toggling view back to the WYSIWYG editor
all other buttons will then be shown again.

- Added jHtmlArea.dispose method - Allows you to remove the WYSIWYG

editor, and go back to having a plain TextArea. Beware, there is a
memory leak when using this method; it's not too bad, but you want
to call this as few a number of times if you can. The memory leak
is due to the way the browsers handle removing DOM Elements.

- Added Indent and Outdent functionality - This includes toolbar buttons
and jHtmlArea.indent and jHtmlArea.outdent buttons.

- Added justifyLeft, justifyCenter, justifyRight functionality and toolbar
buttons.

- Added insertHorizontalRule functionality and toolbar button. This adds a
<hr> tag to the currently selected area.

- Added an "alias" method for jHtmlArea.execCommand named "ec" to help reduce the
file size of the script.

- Added increaseFontSize and decreaseFontSize functionality and toolbar buttons.
The increaseFontSize and decreaseFontSize doesn't currently work in Safari.

- Added forecolor functionality - Changes a font color for the selection or at the
insertion point. Requires a color value string to be passed in as a value argument.

- Fixed bug in jHtmlArea.toString method

- Added jHtmlArea.queryCommandValue method and it's alias "jHtmlArea.qc"

- Added the jHtmlAreaColorPickerMenu plugin/extension that resides within the
"jHtmlAreaColorPickerMenu.js" file. This file includes a somewhat generic color
picker menu that can be used for any purpose, plus it includes the code to wire
up and override the "stock" jHtmlColor.forecolor functionality and inject the new
Color Picker Menu functionality in it's place when you click on the "forecolor"
toolbar button.

- Changed the "execCommand" and "ec" second parameter to default to "false" if not
specified, and third parameter to default to "null" if not specified. This helps to
reduce the overall file size of the script.

- Added support for Toolbar Button Grouping, now with the additional buttons included
in this release, or even when any custom buttons are used, they will be able to display
nicely by "auto-wrapping" to the next line.

- Added a gradient background to the Toolbar Button Groups, with a slight reverse
gradient on the Buttons when the mouse is hovered over.

 

JavaScript, jquery , , ,

jHtmlArea - The all NEW HTML WYSIWYG Editor for jQuery

21. July 2009

The last couple days I spent time working on a new simple, lightweight, extensible HTML WYSIWYG editor that's built on top of jQuery. I know there are a ton of existing editors, but I couldn't seem to find any with a truely simple, lightweight design that allowed for really easy extensibility, and that's built on top of jQuery to take advantage of the cross-platform capabilities that jQuery has to offer. I feel that I've come up with a really nice HTML editor component that has some pretty usefull extensibility points. Allow me to introduce you to jHTMLArea.

You can download jHtmlArea and some examples of using it over at the official project page on CodePlex: http://jhtmlarea.codeplex.com

To the right there's a screenshot of two instances of jHtmlArea in action. The first one is using the "default" configuration, and the second uses a couple of different custom options, including a completely custom "Save" button that's added using one of jHtmlArea's extensibility points.

Using jHtmlArea is As Simple As 1.2.3.

Follow these 3 steps and you'll have jHtmlArea implemented within your application in no time.

1. Add a <TextArea> to your HTML page

2. Add the "jHtmlArea.js", "jHtmlArea.css" and "jHtmlArea.png" files to your website

3. Add the following JavaScript code to your page to turn all TextArea elements into jHtmlArea's:

$(function(){
    $("textarea").htmlarea();
});

It can be as simple as that to use jHtmlArea within your pages to turn any TextArea DOM Elements into nice jHtmlArea WYSIWYG Editors.

Easily Configure Toolbar Buttons

jHtmlArea makes it extremely simple to define your own custom set of Toolbar buttons; just in case you don't want to show the full set of "default" buttons.

You can easily specify them by name within an array that's passed in as one of the options specified when you call the "htmlarea" method:

$("#txtCustomHtmlArea").htmlarea({
    toolbar: ["bold", "italic", "underline", "|", "h1", "h2", "h3", "h4", "h5", "h6", "|", "link", "unlink"]
});

This example will specify the same buttons displayed in the lower screenshot to the right; minus the "Save" button on the far right of the toolbar. I'll show you how to add this button in the next example.

Add Custom Toolbar Buttons

One of the extensibility points that I was wanting to have in an HTML WYSIWYG editor is the ability to easily add any custom buttons to the toolbar. For instance, some times it may be nice to have a "Save" button in the toolbar to allow your users to easily save the contents of the editor.

Here's an example using the above "custom" toolbar buttons list, with a custom "Save" button added:

$("#txtCustomHtmlArea").htmlarea({
    toolbar: ["bold", "italic", "underline", "|", "h1", "h2", "h3", "h4", "h5", "h6", "|", "link", "unlink", "|",
        // This is how to add a completely custom Toolbar Button
        {
            // The CSS Class to assign the Button <a> tag
            css: "custom_disk_button",

            // The Text to display in the buttons alt text / tooltip
            text: "Save",

            // The function to execute when the button is clicked
            action: function(btn) {
                // 'this' = jHtmlArea object
                // 'btn' = jQuery object that represents the <A> "anchor" tag for the Toolbar Button

                alert('SAVE!\n\n' + this.toHtmlString());

                // Add any Ajax Code here to save the contents of the editor

            }
        }
    ]
});

Once the JavaScript code is entered to add the custom "Save" button, we then need to add the buttons display image to the website, and then include the necessary CSS to allow it to be displayed:

What about Localization?

Well, the jHtmlEditor currently only comes with English text for all the button names / tooltips. However, it is extremely simple to specify your own text to use when calling the "htmlarea" to create jHtmlArea editors within the page. You set the Text to be displayed for each button by referencing it by "name". This is the same "name" that is used in the first example to specify which buttons are displayed in the toolbar.

$("#txtCustomHtmlArea").htmlarea({
    // Override any of the toolbarText values - these are the Alt Text / Tooltips shown
    // when the user hovers the mouse over the Toolbar Buttons
    // Here are a couple translated to German, thanks to Google Translate.
    toolbarText: $.extend({}, jHtmlArea.defaultOptions.toolbarText, {
            "bold": "fett",
            "italic": "kursiv",
            "underline": "unterstreichen"
        })
});

Specify CSS File to be used by the Editor

You can also specify a specify CSS file to be used within the Editor itself.

$("#txtCustomHtmlArea").htmlarea({
    css: "style//jHtmlArea.Editor.css"
});

Specify a Callback when the Editor Finishes Loading

It may be nice in some instances to get notified when the editor has finsihed loading in the page so you can perform some kind of action. This is also really simple to do.

$("#txtCustomHtmlArea").htmlarea({
    // Do something once the editor has finished loading
    loaded: function() {
        //// 'this' is equal to the jHtmlArea object

        alert("jHtmlArea has loaded!");

        //this.showHTMLView(); // show the HTML view once the editor has finished loading
    }
});

Call any jHtmlArea object methods easily from jQuery

Another thing is that the jQuery object doesn't directly expose the different jHtmlArea object's methods. However, you can use the "htmlarea" method to call any of them you need to. All you need to do is specify the method by name that you want to call and pass any additional parameters to the "htmlarea" method and it'll return the results.

// Get the HTML string value from within the editor
var html = $("#txtCustomHtmlArea").htmlarea("toHtmlString");

// Insert a specify Image that you want
$("#txtCustomHtmlArea").htmlarea("image", "image.jpg");

The jHtmlArea object has a few more methods, you can find out what they are by referencing the Visual Studio JavaScript Intellisense File ("jHtmlArea-0.5.0-vsdoc.js") or the un-minified source code itself.

Conclusion

As you can see the jHtmlEditor has some really simple extensibility points. I hope you enjoy using this editor as much as I do. Also, if you have any suggestions/issues, please go to the official jHtmlArea project's Issue Tracker and let me know.

JavaScript, JavaScript, jquery, jquery , , , , , , ,

Adding a DotNetKicks Image/Badge via jQuery

20. July 2009

A while ago Jon Galloway posted a short article titled "Adding a DotNetKicks image via JavaScript" which contains the small amount of JavaScript code necessary to add a DotNetKicks.com Image / Badge to your web pages. The DotNetKicks Badge is essentially a link that allows users to go to DotNetKicks.com to vote for you web page, and the badge also displays the total number of "kicks" that your page has received. Since jQuery has become insanely popular since Jon originally posted his JavaScript code, I thought I would post a jQuery version of his code.

Here's a simple demonstration of the DotNetKicks.com Badge that the below jQuery/JavaScript code will generate:

kick it on DotNetKicks.com

To use the below code you just need to follow the following steps:

  1. Create a <DIV> element wher you want the badge to be displayed.
  2. Set the <DIV>'s ID to 'postToolbar'.
  3. Make sure that the jQuery Library is included within the page.
  4. Include the below jQuery / JavaScript code within the page.

 

Here's the jQuery / JavaScript code:

$(function() {
    var currentPageUrl = document.location.protocol + "//" + document.location.host + document.location.pathname;
    $('#postToolbar').append(
            $('<a/>').
                    attr('href', 'http://www.dotnetkicks.com/kick/?url=' + currentPageUrl).
                    css({ border: 'none' }).
                append(
                    $('<img/>').
                        attr('src', 'http://www.dotnetkicks.com/Services/Images/KickItImageGenerator.ashx?url=' + currentPageUrl).
                        css({ border: 'none' })
                )
        );
});

JavaScript, jquery ,