Api 2.0.0 - Documentation

Beta

The SnapEditor API is currently in beta. We don't anticipate any major changes as we have been working on this for more than half a year but we don't guarantee it won't change. Use this at your own risk.

The API is the public interface to a particular SnapEditor instance.

Access

If you have a SnapEditor instance, you can access the API through the instance.

var editor = new SnapEditor.InPlace("editor");
editor.api;

All callbacks are given a SnapEditor event object that contains the API.

var editor = new SnapEditor.InPlace("editor", {
  onSave: function (e) {
    e.api;
  }
});

API Object

The following attributes are available.

el, doc, win, config

The following functions are available.

// Event related
on(), off(), trigger()
// Enable related
enable(), disable(), isEnabled(),
// Content related
getContents(), setContents()
// DOM related
createElement(), createTextNode(), find()
// Dialog related
openDialog(), closeDialog(),
// Action related
activate(), deactivate(), update(), clean(), execAction()
// Range related
getRange(),
isValid(), isCollapsed(), isImageSelected(), isStartOfElement(), isEndOfElement(),
getParentElement(), getParentElements(), getText(), getCoordinates(),
collapse(), unselect(), keepRange(), moveBoundary(),
insert(), surroundContents(), delete(),
select(), selectElementContents(), selectEndOfElement(),
formatBlock(), formatInline(), align(), indent(), outdent(),
insertUnorderedList(), insertOrderedList(), insertHorizontalRule(), insertLink()

Attributes

el

api.el

This is a reference to the DOM element that is editable.

doc

api.doc

This is a reference to the document containing the editable element. This is especially useful when the editable element is inside an iframe.

win

api.win

This is a reference to the window containing the eidtable element. This is especially useful when the editable element is inside an iframe.

config

api.config

This is a reference to the config object passed in when initializing the SnapEditor instance.

Event Related Functions

on()

api.on(<event type>, <callback function>)
api.on(<multiple events as an object>)

on() is used to add event handlers to events triggered by the API.

The event type is a String. When the event type is triggered, the corresponding callback function is called. The callback function will receive a SnapEditor event object as the first argument that will contain the API, as well as any arguments passed through when calling trigger().

on() also accepts an object where the keys are the event types and the values are the callback functions.

SnapEditor will trigger the following events.

// SnapEditor events
"snapeditor.plugins_ready" - when all the plugins have been loaded
"snapeditor.activate" - when the user clicks into a SnapEditor instance to activate it
"snapeditor.ready" - when all activate callbacks are complete
"snapeditor.deactivate" - when the SnapEditor instance deactivates
"snapeditor.update" - triggered by api.update()
"snapeditor.clean" - triggered by api.clean()
// DOM events
// - document events are events that occur on the document
// - outside events are events that occur on the document but not in the editable element
"snapeditor.document_mouseover"
"snapeditor.document_mouseout"
"snapeditor.document_mousedown"
"snapeditor.document_mouseup"
"snapeditor.document_click"
"snapeditor.document_dblclick"
"snapeditor.document_keydown"
"snapeditor.document_keyup"
"snapeditor.document_keypress"
"snapeditor.outside_mouseover"
"snapeditor.outside_mousedown"
"snapeditor.outside_mouseup"
"snapeditor.outside_click"
"snapeditor.outside_dblclick"
"snapeditor.outside_keydown"
"snapeditor.outside_keyup"
"snapeditor.outside_keypress"

For SnapEditor DOM events, outerPageX and outerPageY are available which translates the mouse coordinates inside an iframe to coordinates relative to the outer document.

Other events not listed here may also be triggered. Plugins may trigger their own events and of course, you may also trigger your own events. See the details for trigger().

Examples.

api.on("snapeditor.activate", function (e) {
  console.log("activate called", e.api.getContents());
});
api.on({
  "snapeditor.activate", function (e) {
    console.log("activate called", e.api.getContents());
  },
  "snapeditor.document_click", function (e) {
    console.log("document click called", e.api.getContents());
  }
})

off()

api.off(<event type>[, <callback function>])
api.off(<multiple events in an object>)

off() is used to remove event handlers from the API.

The event type is a String. When given a callback function, it removes that specific callback function for the event type.

When no callback function is given, all callback functions for the event type are removed. This is provided as a convenient way to remove all event handlers. However, we recommend that this be used with care as it will also remove all other event handlers that you may not have attached.

off() also accepts an object where the keys are the event types and the values are the callback functions.

Examples.

var fn1 = function (e) {};
var fn2 = function (e) {};
// Remove a single event handler.
api.on("snapeditor.activate", fn1);
api.off("snapeditor.activate", fn1);
// Remove all event handlers.
api.on("snapeditor.activate", fn1);
api.on("snapeditor.activate", fn2);
api.off("snapeditor.activate");
// Remove multiple event handlers
api.on("snapeditor.activate", fn1);
api.on("snapeditor.deactivate", fn2);
api.off({
  "snapeditor.activate": fn1,
  "snapeditor.deactivate": fn2
});

trigger()

api.trigger(<event type>[, arguments])

trigger() is used to trigger the event handlers attached to the event type. The event handlers will receive a SnapEditor event object as their first argument that will contain the API. Extra arguments can be passed through to the event handlers using the arguments array. The event handler will see the extra arguments as separate arguments after the event that is passed through.

Event types can be any String. However, collisions can occur. To prevent this, we suggest namespacing custom events. A namespace is created using a '.'. The SnapEditor event system only supports one level of namespacing. An example would be "custom_namespace.activate".

Examples.

// Trigger without arguments.
api.on("custom_namespace.activate", function (e) {
  var html = e.api.getContents();
});
api.trigger("custom_namespace.activate");
// Trigger with arguments.
api.on("custom_namespace.show", function(e, message, status) {
  var html = e.api.getContents();
});
api.trigger("custom_namespace.show", ["Hello World", 200]);

Enable Related Functions

enable()

api.enable()

enable() enables the particular instance of SnapEditor. By default, each instance of SnapEditor is enabled.

disable()

api.disable()

disable() disables the particular instance of SnapEditor. This means the outline on hover does not show up and clicking inside this instance of SnapEditor does nothing.

isEnabled()

api.isEnabled()

isEnabled() returns true if the particular instance of SnapEditor is enabled. Otherwise, it returns false.

Content Related Functions

getContents()

api.getContents()

getContents() returns the HTML contents of the editor as a String. Use this to get the contents instead of using innerHTML of the editable element itself because SnapEditor runs certains check before returning the content.

Example.

// Do this.
var html = api.getContents();
// Don't do this.
var html = api.el.innerHTML;

setContents()

api.setContents(<HTML String>)

setContents() takes the given HTML String and sets the contents of the editor. Use this to set the contents instead of using innerHTML of the editable element itself because SnapEditor runs certains check before setting the content

Example.

// Do this.
api.setContents("Hello World");
// Don't do this.
api.el.innerHTML = "Hello World";

DOM Related Functions

createElement()

api.createElement(<tag>)

createElement() is a shortcut to the document's createElement(). Use this when creating elements to be inserted into SnapEditor instead of the document's createElement(). This is useful to prevent errors when inserting elements into an iframe.

Example.

var el = api.createElement("div");

createTextNode()

api.createTextNode(<text>)

createTextNode() is a shortcut to the document's createTextNode(). Use this when creating textnodes to be inserted into SnapEditor instead of the document's createTextNode(). This is useful to prevent errors when inserting textnodes into an iframe.

Example.

var textnode = api.createTextNode("text");

find()

api.find(<selector>)

find() finds all the elements that match the given CSS selector within the editable element. The matched elements are returned in an array even when there is only a single match. An empty array is returned when there are no matches.

Examples.

// No match.
var empty = api.find("this doesn't exist"); // []
// Single match.
var single = api.find("#single"); // [<element>]
// Multiple matches.
var multiple = api.find("p"); // [<element>, <element>, <element>]

Dialog Related Functions

openDialog()

api.openDialog(<name>, <SnapEditor Event Object>, [extra args])

For more details, check out the Dialog docs.

closeDialog()

api.closeDialog(<name>)

For more details, check out the Dialog docs.

Action Related Functions

activate()

api.activate()

activate() starts the activation procedure of the editor and places the cursor at the beginning of the content.

deactivate()

api.deactivate()

deactivate() starts the deactivation procedure of the editor.

update()

api.update()

update() should be called when there are any changes to the contents of the editor. It lets the editor know that it needs to kick off the update process, such as updating the snap elements.

clean()

api.clean([start element, end element])

clean() triggers the cleaner.

When no arguments are passed in, the cleaner cleans the area where the current selection is.

When start element and end element are given, the cleaner cleans the area from the start element to the end element.

Note that the cleaner may decide to clean more than specified. The selection, start element, and end element are only hints.

execAction()

api.execAction(<name>, <SnapEditor Event Object>, [extra args])

For more details, check out the Action docs.

Range Related Functions

getRange()

api.getRange([element])

When getRange() is called without arguments, a SnapEditor range object is returned that represents the current selection.

When getRange() is called with a DOM element, a SnapEditor range object is returned that represents the element.

This is useful when you want to save the range for later use.

Examples.

// Get the current selection.
api.getRange();
// Get the range that represents the first <p>.
var ps = api.find("p");
api.getRange(ps[0]);

isValid()

api.isValid()

isValid() returns true when the current selection is valid. Usually, isValid() will return false when no selection has been made or the selection has been removed.

isCollapsed()

api.isCollapsed()

isCollapsed() returns true when the selection is collapsed. A selection is collapsed when it looks like a caret. That is, a selection is collapsed when the start and end of the selection is the same. isCollapsed() returns false otherwise.

isImageSelected()

api.isImageSelected()

isImageSelected() returns true when an image is currently selected. isImageSelected() returns false otherwise.

isStartOfElement()

api.isStartOfElement(<element>)

isStartOfElement() returns true if the selection is at the start of the element. The selection is at the start if there are no other width-generating characters in between the start of the element and the selection. isStartOfElement() returns false otherwise.

isEndOfElement()

api.isEndOfElement(<element>)

isEndOfElement() returns true if the selection is at the end of the element. The selection is at the end if there are no other width-generating characters in between the end of the element and the selection. isEndOfElement() returns false otherwise.

getParentElement()

api.getParentElement([selector])

When no arguments are passed to getParentElement(), it returns the closest common ancestor. When the selection is collapsed, the closest common ancestor is the immediate parent element that contains the selection. When the selection is not collapsed, the closest common ancestor is the parent element that encompasses the entire selection.

When a CSS selector is given, getParentElement() returns the closest common ancestor that matches.

If no match can be found before inside the editable element, null is returned.

Examples.

// Get the parent element.
var parent = api.getParentElement();
// Get the parent element that matches.
var matchParent = api.getParentElement("table");
// No match returns null.
var noParent = api.getParentElement("no match");

getParentElements()

api.getParentElements([selector])

getParentElements() behaves similarly to getParentElement(). The only difference is that it returns an array of 2 elements. The first element represents the closest common ancestor to the start of the selection. The second element represents the closest common ancestor to the end of the selection.

getText()

api.getText()

getText() returns the text of the current selection. Note that this only returns the text. It does not return the HTML.

getCoordinates()

api.getCoordinates()

getCoordinates() returns the coordinates of the selection as an object. The coordinates represent a bounding box around the selection. Note that the coordinates are relative to the outermost document. This is useful when dealing with iframes.

{
  top: <Integer>,
  bottom: <Integer>,
  left: <Integer>,
  right: <Integer>
}

Note that in IE8, the left and right are not always the left and right of the bounding box. Instead, the left is sometimes the left of the start of the selection and the right is sometimes the right of the end of the selection. This is unfortunately a problem with IE8 itself.

collapse()

api.collapse(<true/false>)

When true is passed to collapse() the current selection is collapsed to the start of the selection.

When false is passed to collapse() the current selection is collapsed to the end of the selection.

unselect()

api.unselect()

unselect() unselects the current selection. Be careful with this because a lot of SnapEditor functions require a selection to be present to work properly. This is provided because there are certain cases where unselecting is required. However, be sure to select something before your code finishes executing.

keepRange()

api.keepRange(<function>)

keepRange() saves the current selection, executes the given function, then reselects the selection.

In order to keep the range, a span is inserted at the start of the selection and another span is inserted at the end of the selection. The function will receive the start and end spans as arguments.

Because the spans are required to reselect the selection, the function must be careful not to remove these spans. However, they may be moved around. Note though that if the spans are moved, the reselection may not resemble the original selection.

Example.

// Remove the starting textnode while keeping the range.
api.keepRange(function (startEl, endEl) {
  var nextEl = startEl.nextSibling;
  if(nextEl && nextEl.nodeType === 3) {
    nextEl.parentNode.removeChild(nextEl);
  }
});

moveBoundary()

api.moveBoundary(<boundaries>, <element>)

moveBoundary() moves the start or end of the selection to the start or end of the given element.

The boundaries argument tells which boundary of the selection to move and which boundary of the element to move to. The first start/end refers to the boundary of the selection and the second start/end refers to the boundary of the element. The following are the possible values of the boundaries argument. Note that these values are case insensitive.

"starttostart", "starttoend", "endtostart", "endtoend"

Example.

// This moves the current selection's end to the start of the given element.
var lastP = api.find("p").pop();
api.moveBoundary("endtostart", lastP);

insert()

api.insert(<HTML or DOM element>)

insert() inserts the given HTML string or DOM element.

Note that when given a DOM element, the actual DOM element is not inserted. The string representation of the element is inserted instead. Hence, do not expect to be able to reference the inserted content using the original DOM element.

Examples.

// Insert HTML.
api.insert("<bold>This is bold</bold>");
// Insert a DOM element.
var el = api.createElement("p");
el.innerHTML = "Hello";
api.insert(el);
// The following will not actually modify the inserted <p> in the editor.
el.innerHTML = "World";

surroundContents()

api.surroundContents(<element>)

surroundContents() wraps the currently selected content with the given element.

delete()

api.delete()

delete() deletes the contents of the current selection.

select()

api.select([SnapEditor range object or DOM element])

When select() is called without an argument, it selects the current selection.

When select() is called with a SnapEditor range object, it selects the given range.

When select() is called with a DOM element, it selects the the given DOM element.

Examples.

// Select the current selection.
api.select();
// Select a saved range.
var range = api.getRange();
api.select(range);
// Select a DOM element.
var firstP = api.find("p")[0];
api.select(firstP);

selectElementContents()

api.selectElementContents(<element>)

selectElementContents() selects the contents of the given element.

selectEndOfElement()

api.selectEndOfElement(<element>)

selectEndOfElement() places the selection at the end of the given element.