Skip to content

Instantly share code, notes, and snippets.

@mattcdavis1
Last active September 23, 2015 06:02
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mattcdavis1/693e35df2d1b877abc62 to your computer and use it in GitHub Desktop.
Save mattcdavis1/693e35df2d1b877abc62 to your computer and use it in GitHub Desktop.
Strikethrough
$.Redactor.prototype.strikethrough = function()
{
return {
init: function() {
var button = this.button.add('strikethrough', 'Strikethrough');
this.button.setAwesome('strikethrough', 'fa-strikethrough');
this.button.addCallback(button, this.strikethrough.show);
},
show: function() {
var range = this.range;
var commonAncestorContainer = range.commonAncestorContainer;
var commonAncestorContainerNodeName = commonAncestorContainer.nodeName.toLowerCase();
// if the common ancestor is a del or has a parent del, unwrap it
parentDel = $(commonAncestorContainer).closest('del');
while(parentDel.length) {
parentDel.contents().unwrap();
parentDel = parentDel.parents('del');
}
// if the common ancestor has a single direct child of del,
// unwrap it and we're done
if( $(commonAncestorContainer).children().length == 1
&& $(commonAncestorContainer).find('del').length) {
var $delChild = $(commonAncestorContainer).find('del');
if($delChild.length) {
$delChild.contents().unwrap();
}
} else {
// get parent element
var parentElement = commonAncestorContainer;
if(parentElement.nodeName.toLowerCase() == '#text') {
parentElement = commonAncestorContainer.parentNode;
}
// create fragment from selection
var textFragment = range.extractContents();
// if the text fragment has a single direct child of del,
// unwrap it and we're done
if( $(textFragment).children().length == 1
&& $(textFragment).find('del').length ) {
var $delChild = $(textFragment).find('del');
if($delChild.length) {
$delChild.contents().unwrap();
}
range.insertNode(textFragment);
} else {
// remove any child del tags
while(delChildNode = textFragment.querySelector('del')) {
$(delChildNode).contents().unwrap();
}
// if the selected text interesects an del node, remove it
childDelNodes = $(parentElement).find('del');
$.each(childDelNodes, function() {
var node = this;
if(range.intersectsNode(node)) {
$(node).contents().unwrap();
}
});
// remove any child element del nodes
if(parentElement.nodeName.toLowerCase() == "del") {
$(parentElement).contents().unwrap();
range.insertNode(textFragment);
} else {
var delNode = document.createElement("del");
delNode.appendChild(textFragment);
range.insertNode(delNode);
}
}
}
// remove empty and nested del tags
this.$box.find('del del').each(function() {
$(this).contents().unwrap();
});
this.$box.find('del:empty').remove();
// sync with redactor so changes aren't overwritten
this.code.sync();
// add css class
this.$box.find('del').addClass('diff');
}
};
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment