New Features in the jQuery WYSIWYG HTML Editor

Damyan Petev / Thursday, May 10, 2012

Not so long ago we introduced our very own “what you see is what you get” HTML Editor control and showed you how you can provide rich text editing for your users relying on JavaScript/jQuery or the comfort of ASP.NET MVC.  I’ll skip further explanations as to why such functionality is useful and virtually needed for even simple user input – you can read on that in the first blog. As for how the control evolved – it was Community Technology Preview and it is re-introduced as CTP for the new release as well. You could say the first version was somewhat a rough cut and that’s not a bad thing – means it had plenty of room for improvement and, therefore, plenty of new and exciting enhancements for us to share with you now. So what’s new?

Design and interaction

First and foremost, along with functionality improvements, the editor got user interaction changes to provide for a more instinctive experience. There are now much more ways to format content and they have been regrouped in thematic toolbars so you can easily find a feature and the features themselves have received some polishing to make their impact much more obvious:

The enriched fonts dropdown in the HTML Editor, previewing the available typefaces.

This is the enriched fonts dropdown, that now displays each in its respective style to give an idea of how text would look like. The number of fonts available has more than doubled and there are even some (exotic at least in my view) ornament typefaces, like Webdings and Wingdings –those are the two fonts with symbols. They have a whole bunch of cool and useful ‘glyphs’ – like Wingdings’s smiley face at ‘J’. All groups can now be collapsed and expanded via those arrows at the beginning of each. Similarly, most dropdowns now preview their effects. Adding to that, other actions that open new UI ‘windows’ now use popover style (like the ones you’d see in the Grid) and color pickers:

HTML Editor's combos previewing their effects and new user interactions such as color picker and toolbar collapsing and expanding.

There are also new split-buttons (like the text color) that also save up some space as they have two actions – like bullets and numbering, and the default or last used action will take the place on the toolbar.

Finally, everything is localizable - all tooltips for the toolbar actions, font size and headings, along with the list of fonts. Yes, the fonts are not hardcoded, in fact there are two separate lists for Windows or Mac users and all that can be tailored to fit the users.

Toolbars and features

From what you may or may not see on the first shot, the toolbars got shifted around a bit and the ‘source’ button is no longer up there, but it found its new spot just below the editing area, in front the DOM path. Here’s a list of the default toolbars (new functionalities are bolded):

  • Text toolbar – including text decorations and properties, increase/decrease size, fonts, sizes and headers
  • Formatting toolbar – alignment, bullets, numbering, indent, text color and background
  • Insert objects toolbar – add images, links, tables; add or remove table rows and columns
  • Copy Paste toolbar – All new! Clipboard support for cut/copy/paste as well as Undo and Redo operations!

A very important note should be made here – some of the new functionality internally rely on the execCommand() method that is available on all browsers, but the range of commands browsers allow will vary somewhat. Let me give you an example – copy and paste clipboard access is something quite dangerous to allow to a JavaScript code – it can override content and is generally considered a security threat and as such half the browsers out there will not allow it. For Firefox there’s a way to opt in for that via Configurable Security Policies, so such might be available for other browsers. The editor will check that and disable those buttons accordingly. However, user interaction is not restricted, so keyboard shortcuts (like Ctrl + C ) and right-click menu options will always work! And yes, things like copying text and content as a whole from web pages or word documents is still available!

Enhanced API

It only seems logical to start this section with this – yes, there are finally methods available to get and set content! But that was somewhat expected and there are still a dozen of new things you can now enjoy as a developer. Firstly, though, you might want to check our Deployment Guide to reflect all the new stuff around using the resource loader, migrating versions, theming, localization and so on. Once you have that covered you can easily add the scripts required and a HTML Editor widget to you page. Back to API - almost all the settings, methods and events below are new or at least tweaked in some way.

Settings

Besides letting the user control the toolbars via collapsing, all the toolbars have their bool property to show/hide them (that means you could change options in run time as well and the editor will reflect the change). And then you have a separate settings specific for each toolbar – like selecting some options as pre-set for the user or even whether the group is expanded or not:

  1. $("#editor").igHtmlEditor({
  2.     width: "650px",
  3.     showFormattingToolbar: true,
  4.     showTextToolbar: true,
  5.     showInsertObjectToolbar: true,
  6.     showCopyPasteToolbar: true,
  7.     toolbarSettings: [{
  8.         name: "textToolbar",
  9.         isItalic: true,
  10.     },
  11.     {
  12.         name: "copyPasteToolbar",
  13.         expanded: false
  14.     }]
  15. });

Events

To improve you control and potentially help you deliver better experiences, the WYSIWYG Editor widget now has quite a few events you can handle to react accordingly. You have events that fire when operations like copy, paste, undo or redo occur – yes, even if the user does that via keyboard shortcuts. Then there are general events to tell you when toolbars are (about to be) collapsed or expanded or actions from them are (about to be) executed. Based on your needs you can apply logic at just the right time and the event arguments of course will provide you extra information as expected:

  1. //event handle
  2. $(document).delegate("#testEditor", "ightmleditoractionexecuting", function (evt, ui) {
  3.     alert("Action executing: " + ui.actionName + " from toolbar: " + ui.toolbar);
  4. });

Methods

As mentioned you can get and set the contents and both methods have format option, that lets you choose if you want just the text of the full html markup:

  1. function AddCommentText() {
  2.     var test = $('#testEditor').igHtmlEditor("getContent", "text");
  3.     $('#Log').text(test);
  4. }
  5. function AddCommentHtml() {
  6.     var test = $('#testEditor').igHtmlEditor("getContent", "html");
  7.     $('#Log').html(test);
  8. }

Custom Toolbars

Of course, that customization option is far from gone! There are numerous cases where you could use your own actions to save time or simply to add some specific functionality to the control. Keep in mind all icons are set via CSS to promote the usage of CSS sprites. Here’s an example of how you can define you own – defining name, expand/collapse icons (in this case the default ones) and add items to it. Items can be either buttons or combos and have names (becomes the action name). Icon and tooltip are can be set in each items properties. The scope set is required for the handler method:

  1. $('#testEditor').igHtmlEditor({
  2.      customToolbars: [{
  3.          name: 'testToolbar',
  4.          expanded: true,
  5.          collapseButtonIcon: "ui-igbutton-collapse",
  6.          expandButtonIcon: "ui-igbutton-expand",
  7.          items: [{
  8.              type: 'button',
  9.              name: 'testing',
  10.              scope: this,
  11.              props: {
  12.                  buttonTooltip: {
  13.                      value: "Testing tooltip",
  14.                      action: '_tooltipAction'
  15.                  },
  16.                  boldButtonIcon: {
  17.                          value: "ui-igbutton-custom-icon",
  18.                          action: '_buttonIconAction'
  19.                  }
  20.              },
  21.              handler: SnippetAction
  22.          }]
  23.      }]
  24.  });

The HTML Editor with Italic enabled and Copy/Paste toolbar collapsed with initialization and a custom toolbar.

Notice the last button with small logo I assigned with CSS. Then you have you handle method, in this case I decided I want a snippet action resembling Visual Studio somewhat, so I would replace key words with actual snippets (just ‘switch’ in the demo):

  1. // Custom toolbar action function:
  2. function SnippetAction(workspaceDocument, ui) {
  3.     var switchCS = "switch (caseSwitch)<br/>{<br/><blockquote>case 1:<br/>//action 1;<br/>break;<br/>case 2:<br/>//action 2;<br/>break;<br/>default:<br/>//action 3;<br/>break;</blockquote><br/>}";
  4.     if (ui.selectedItem[0].textContent.indexOf("switch") != -1) {
  5.         ui.selectedItem[0].parentNode.innerHTML = switchCS;
  6.     }
  7. }

As you can see the function receives two arguments – the first being the DOMDocument of the editor’s iframe and the second provides useful information , access to the action, item, toolbar and most importantly the selected item. You check if the user has selected an image or some text node and in this case we check to see if the selection contains ‘switch’ and replace the markup with the snippet’s and the result from that is:

The HTML Editor a custom toolbar: result after the handler function's execution.

Wrapping Up

The ‘new’ WYSIWYG HTML Editor now includes more options for text manipulating, improved design and interactions for better user experience. It still maintains a number of features  like inserting tables, images and links, clipboard support allowing formatted text from MS Word or another web page to be pasted and edited in the control and now dedicated toolbar for clipboard actions. It allows for more control when defining settings or handling user interactions with events. This is just at CTP state and as said that means there’s more polishing coming!

Meanwhile, you can try it right now by visiting our online samples for the HTML Editor. Also you can download a fully functional unlimited trial of NetAdvantage for jQuery and the Demo Project for this Blog – an APS.NET MVC application including implementation of custom toolbar and item as shown above, definition using the MVC wrapper’s model and the Editors Metro looks!

Follow us on Twitter @Infragistics and join the competition on Facebook and don’t forget to vote for us in the Code Project’s Reader’s Choice Awards!