YUI Library Home

Site Search (YDN & YUIBlog):

# YUI Library Examples: Rich Text Editor: Calendar Plugin

# Rich Text Editor: Calendar Plugin

This example adds a button to the Rich Text Editor's Toolbar that displays a Calendar Control for choosing dates. It also demonstrates how to manage the state of a custom button.

Click the Date button () in the Toolbar to display the Calendar Control, then select a date and it will be placed inside the Editor.

You can also click on a date that has been inserted in the Editor and the Date button will enable. When the Date button is enabled and you click it the corresponding date will be selected in the Calendar Control when it is displayed.

View example in new window.

This is some more test text. <font face="Times New Roman">This is some more test text. This is some more <b>test <i>text</i></b></font>. This is some more test text. This is some more test text. This is some more test text. This is some more test text. This is some more test text. This is some more test text. This is some more test text.

## Setting up the Editor's HTML

Setting up the Editor's HTML is done by creating a `textarea` control on the page.

<form method="post" action="#" id="form1"> <textarea id="editor" name="editor" rows="20" cols="75"> This is some more test text. <font face="Times New Roman">This is some more test text. This is some more <b>test <i>text</i></b></font>. This is some more test text. This is some more test text. This is some more test text. This is some more test text. This is some more test text. This is some more test text. This is some more test text. </textarea> </form>

## Setting up the Editor's Javascript

Once the `textarea` is on the page, then initialize the Editor like this:

(function() { //Setup some private variables var Dom = YAHOO.util.Dom, Event = YAHOO.util.Event, cal = null, //Reference to the calendar object we are about to create selectedDate = null; //Reference to the current selected date. //The Editor config var myConfig = { height: '300px', width: '600px', animate: true, dompath: true, focusAtStart: true }; //Now let's load the Editor.. var myEditor = new YAHOO.widget.Editor('editor', myConfig); })();

## Creating the Toolbar Button and Menu

Now we can create a button and add it to the Editor's Toolbar. First we subscribe to the Editor's `toolbarLoaded` Custom Event. From inside that function we will set up a new button config object literal with the following properties:

- type: (push, menu, split, spin, select, color)
- label: The text string displayed on the button
- value: The value is also called the Command for the button.
- menu: A `YAHOO.widget.Overlay` instance to be used as a menu.

Now add it to the Toolbar group called "insertitem" like this: `myEditor.toolbar.addButtonToGroup(dateConfig, 'insertitem');`

//Snipped from above var myEditor = new YAHOO.widget.Editor('editor', myConfig); //Subscribe to the toolbarLoaded Custom event fired in render myEditor.on('toolbarLoaded', function() { //Setup the config for the new "Insert Date" button var dateConfig = { type: 'push', //Using a standard push button label: 'Insert Date', //The name/title of the button value: 'insertdate', //The "Command" for the button menu: function() { //Create the Overlay instance we are going to use for the menu var menu = new YAHOO.widget.Overlay('insertdate', { width: '210px', height: '220px', xy: [-9000,-9000], visible: false }); //Setting the body to the container that we wish to render the calendar into. menu.setBody('<div id="cal1Container"></div>'); //Set the context to the bottom left corner of the Insert Date button menu.beforeShowEvent.subscribe(function() { menu.cfg.setProperty('context', [ myEditor.toolbar.getButtonByValue('insertdate').get('element'), 'tl', 'bl' ]); }); //Show the Overlay and prep the calendar's selected date menu.showEvent.subscribe(function() { cal.deselectAll(); Dom.removeClass(cal.cells, 'selected'); //selectedDate is populated in the onAvailable call later on.. if (selectedDate != null) { cal.cfg.setProperty('selected', selectedDate); cal.cfg.setProperty('pagedate', new Date(selectedDate), true); selectedDate = null; } cal.render(); }); menu.render(document.body); menu.element.style.visibility = 'hidden'; //return the Overlay instance here return menu; }() //This fires the function right now to return the Overlay Instance to the menu property.. }; //Add the new button to the Toolbar Group called insertitem. myEditor.toolbar.addButtonToGroup(dateConfig, 'insertitem'); }); myEditor.render(); })();

## Handling the Button's State on Node Change

After we have created the new button and added it to the Toolbar, we need to listen for events to trigger our new button.

We can do that by listening to the `afterNodeChange` CustomEvent.

The `before/afterNodeChange` events are fired when something interesting happens inside the Editor. Clicks, Key Presses, etc.

From inside the `afterNodeChange` Event we can get access the the last element (or current element) that was affected. We get access to this element via: `obj._getSelectedElement()`

Now that we have a reference we can use standard DOM manipulation to change the element and the Toolbar.

In this case, we are grabbing the current element and checking to see if it or its parent has a className of date.

If it does, then we are populating the var `selectedDate` with the `innerHTML` of the element.

We are also using this opportunity to select the "insertdate" button on the toolbar, so that it becomes active. We are doing this with the following command:`this.toolbar.selectButton(this.toolbar.getButtonByValue('insertdate'))`

`this.toolbar.getButtonByValue('insertdate')` this method will return a Button reference from the toolbar, that we can pass to `this.toolbar.selectButton()` and cause the button to be selected.

On the next `nodeChange` Event, our button will be disabled automatically and this handler will re-select it if it is needed.

//Snipped from above myEditor.toolbar.addButtonToGroup(dateConfig, 'insertitem'); //Listening to the afterNode Change Custom Event myEditor.on('afterNodeChange', function() { var el = this._getSelectedElement(); //Currently Selected Element //Does it or its parent have a class of 'date' if (Dom.hasClass(el, 'date') || Dom.hasClass(el.parentNode, 'date')) { //Set the button to selected this.toolbar.selectButton(this.toolbar.getButtonByValue('insertdate')); //Capture the innerHTML of the element and use it in the Menu's show Event. if (Dom.hasClass(el.parentNode, 'date')) { selectedDate = el.parentNode.innerHTML; } else { selectedDate = el.innerHTML; } var _button = this.toolbar.getButtonByValue('insertdate'); _button._menu.hide(); } }, myEditor, true); myEditor.toolbar.on('insertdateClick', function(ev) { var calDate = ' <span class="date">' + (ev.calDate.getMonth() + 1) + '/' + ev.calDate.getDate() + '/' + ev.calDate.getFullYear() + '</span> '; this.execCommand('inserthtml', calDate); var _button = this.toolbar.getButtonByValue('insertdate'); _button._menu.hide(); }, myEditor, true);

## Rendering the Calendar and Handle Date Selection

Now we add this code at the bottom to be activated when the Element `cal1Container` becomes available in the DOM.

Once that Element is active on the page, we can now build and render our Calendar control.

Notice, that we are subscribing to the Calendar's `selectEvent` to actually execute the insertdateClick event for the Editor.

From there, we get a button reference and call the menu's hide method to hide the Calendar.

//Snipped from above myEditor.render(); Event.onAvailable('cal1Container', function() { //Create the new Calendar instance cal = new YAHOO.widget.Calendar('cal1', 'cal1Container'); //Setup the selectEvent cal.selectEvent.subscribe(function() { var calDate = cal.getSelectedDates()[0]; //This line will fire the event "insertdateClick" that we subscribed to above.. this.toolbar.fireEvent('insertdateClick', { type: 'insertdateClick', calDate: calDate }); }, myEditor, true); //render the Calendar cal.render(); });

## Styling the Button

There are 2 important states to style a button in the toolbar.

First is the default state, that can be accessed via this CSS rule: `.yui-skin-sam .yui-toolbar-container .yui-toolbar-insertdate span.yui-toolbar-icon`

Second is the selected state, that can be accessed via this CSS rule: `.yui-skin-sam .yui-toolbar-container .yui-button-insertdate-selected span.yui-toolbar-icon`

`.yui-toolbar-container` is the class applied to the top-most container of the toolbar.

`.yui-toolbar-icon` is an extra `SPAN` injected into the button for spriting an image.

`.yui-toolbar-VALUE` is a dynamic class added to the button based on the `value` passed into the buttons config. It is used for specific styling of a button that may appear in several places on the page.

## The Style Rules to Create the Calendar Button in this Example

.yui-skin-sam .yui-toolbar-container .yui-toolbar-insertdate span.yui-toolbar-icon { background-image: url( assets/calendar_default.gif ); background-position: 1px 0px; } .yui-skin-sam .yui-toolbar-container .yui-button-insertdate-selected span.yui-toolbar-icon { background-image: url( assets/calendar_active.gif ); background-position: 1px 0px; }

## Full Example Javascript Source

(function() { var Dom = YAHOO.util.Dom, Event = YAHOO.util.Event, cal = null, selectedDate = null; var myConfig = { height: '300px', width: '600px', animate: true, dompath: true, focusAtStart: true }; YAHOO.log('Creating Editor', 'info', 'example'); var myEditor = new YAHOO.widget.Editor('editor', myConfig); myEditor.on('toolbarLoaded', function() { YAHOO.log('Editor Toolbar loaded', 'info', 'example'); var dateConfig = { type: 'push', label: 'Insert Date', value: 'insertdate', menu: function() { var menu = new YAHOO.widget.Overlay('insertdate', { width: '210px', height: '220px', xy: [-9000,-9000], visible: false }); menu.setBody('<div id="cal1Container"></div>'); menu.beforeShowEvent.subscribe(function() { menu.cfg.setProperty('context', [ myEditor.toolbar.getButtonByValue('insertdate').get('element'), 'tl', 'bl' ]); }); menu.showEvent.subscribe(function() { cal.deselectAll(); Dom.removeClass(cal.cells, 'selected'); if (selectedDate != null) { cal.cfg.setProperty('selected', selectedDate); cal.cfg.setProperty('pagedate', new Date(selectedDate), true); selectedDate = null; } cal.render(); }); menu.render(document.body); menu.element.style.visibility = 'hidden'; return menu; }() }; YAHOO.log('Adding new button (insertdate) to toolbar', 'info', 'example'); myEditor.toolbar.addButtonToGroup(dateConfig, 'insertitem'); myEditor.on('afterNodeChange', function() { var el = this._getSelectedElement(); if (Dom.hasClass(el, 'date') || Dom.hasClass(el.parentNode, 'date')) { YAHOO.log('We found an element with the class of (date) select button', 'info', 'example'); this.toolbar.selectButton(this.toolbar.getButtonByValue('insertdate')); if (Dom.hasClass(el.parentNode, 'date')) { selectedDate = el.parentNode.innerHTML; } else { selectedDate = el.innerHTML; } } var _button = this.toolbar.getButtonByValue('insertdate'); _button._menu.hide(); }, myEditor, true); myEditor.toolbar.on('insertdateClick', function(ev) { YAHOO.log('insertdateClick: ' + YAHOO.lang.dump(ev), 'info', 'example'); var calDate = ' <span class="date">' + (ev.calDate.getMonth() + 1) + '/' + ev.calDate.getDate() + '/' + ev.calDate.getFullYear() + '</span> '; this.execCommand('inserthtml', calDate); var _button = this.toolbar.getButtonByValue('insertdate'); _button._menu.hide(); }, myEditor, true); }); myEditor.render(); Event.onAvailable('cal1Container', function() { YAHOO.log('Found (#cal1Container) - render the calendar', 'info', 'example'); cal = new YAHOO.widget.Calendar('cal1', 'cal1Container'); cal.selectEvent.subscribe(function() { var calDate = cal.getSelectedDates()[0]; YAHOO.log('Calendar selectEvent: (' + calDate + ')', 'info', 'example'); this.toolbar.fireEvent('insertdateClick', { type: 'insertdateClick', calDate: calDate }); }, myEditor, true); cal.render(); }); })();

## Configuration for This Example

You can load the necessary JavaScript and CSS for this example from Yahoo's servers. Click here to load the YUI Dependency Configurator with all of this example's dependencies preconfigured.

### YUI Logger Output:

Note: Logging and debugging is currently turned off for this example.

Reload with logging
and debugging enabled.

### Rich Text Editor Examples:

### More Rich Text Editor Resources:

- User's Guide (external)
- API Documentation
- Cheat Sheet PDF (external)

Copyright © 2010 Yahoo! Inc. All rights reserved.

Privacy Policy - Terms of Service - Copyright Policy - Job Openings