Skip to content

Instantly share code, notes, and snippets.

@micahasmith
Created November 11, 2011 20:08
Show Gist options
  • Star 5 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save micahasmith/1359080 to your computer and use it in GitHub Desktop.
Save micahasmith/1359080 to your computer and use it in GitHub Desktop.
Wrap a selection in CKEditor with Rangy
/**
* allows you to wrap or insert an html tag over a selection/range using rangy
* @param iframe the CKEditor iframe html element
* @param tagName string representation of the tag, such as 'a' for anchor
* @param withNodeFunc function to allow outside modification of the element before injecting/wrapping
*/
function wrapOrInsert(iframe, tagName, withNodeFunc) {
var iframedoc = iframe.contentDocument || iframe.contentWindow.document,
tag = iframedoc.createElement(tagName),
selection = rangy.getIframeSelection(iframe),
selectionRange = selection.getRangeAt(0);
//let the caller do something with the element
withNodeFunc(tag);
//since you can't wrap something with an image tag
if (tagName === 'img') {
selectionRange.collapse(false);
selectionRange.insertNode(tag);
} else if (tagName === "a" && selection.isCollapsed) {
//provide some default text for an anchor
selectionRange.collapse(false);
tag.appendChild(iframedoc.createTextNode('link'));
selectionRange.insertNode(tag);
} else {
selectionRange.surroundContents(tag);
}
//detach rangy
selection.detach();
}
/**
* Example on how to call the function, let's say on a jquery document.ready
* It'll wrap the selection in a span
*/
$(function(){
//first, lets get the iframe that the ckeditor is in
var iframe=$(".ckeditor iframe");
//we put the [0] on the end of the jquery item, since that will cast it to a DOM element (see http://stackoverflow.com/questions/6974582/jquery-object-and-dom-element)
// and, we'll pass an empty callback, since we don't want to do anything with the span after its created
wrapOrInsert(iframe[0],"span",function(){});
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment