Monday, September 28, 2009

Quick Tip: Accessing the Contents of a FCKEditor Box

Today I found myself needing a way to access the current contents of a FCKEditor instance on a web page via Javascript (I needed to create a "preview" dialog box that would show the user what the content would look like when published).  After some searching on Google, I learned that by instantiating FCKEditor on the page, I had access to the FCKEditor API and could access the content with the following statement:

var editorContent = FCKeditorAPI.GetInstance("postText").GetXHTML(true);

...where "postText" is the id value ("instanceName") of the editor.

Wednesday, September 9, 2009

jQuery Tip: Storing and Retrieving Object Properties with the Data() Function

The jQuery data() function allows you to store data "within" a DOM object by associating a property name with a value.  The first line of the code below assigns the value "bar" to the property name "foo" associated with the <form> element on the page, while the second line retrieves the stored value:

var fooValue= $("form").data("foo");

It's a useful technique for adding metadata to a DOM element.

The jQuery plugin I'm currently working on associates several pieces of metadata with certain DOM elements on the page.  It occurred to me yesterday that it might be cleaner to store all of that metadata under one property (one namespace) in the DOM element, reducing the possibility of my plugin interfering with any other code might also store data using the data() function.  But I wasn't quite sure how I would retrieve the individual metadata values.

Turns out the solution is quite simple:  you can retrieve the object sorted in the namespace property, then reference the individual properties within the namespace using dot notation:

  var settings= {
     denoteDirtyForm: true,
  var showDirtyForm= $("form").data("myNamespace").denoteDirtyForm;
  var dirtyClass= $("form").data("myNamespance").dirtyFieldClass;

So it looks like there's no real limit to the amount or complexity of data you can associate with a DOM element using data().