Skip to content Skip to sidebar Skip to footer

Weird Behavour Wysiwyg?

I have a code to wrap elements around text it works fine until i try the following format in my editor: Test

Solution 1:

WYSIWYG is hard. Especially with HTML, which is nothing what it looks like. I'm just guessing here, but if you start with

<u>Test</u>

ant you select T in WYSIWYG then the actual selected code will probably be <u>T. Since you can't wrap that in strong (because <strong><u>T</strong> is not valid markup then the editor will wrap everything before the tag in strong and everything after tag in strong, which results in

<strong></strong><u><strong>T</strong>es<strong>t</strong></u><strong></strong>

that you are getting.

I to avoid that you could check if the text that you are wrapping has the lenght of 0, end then if so - not wrap it with anything.

Solution 2:

I'd suggest using DOM manipulation to wrap text nodes within the selection individually. My Rangy library can help a little with this, providing splitBoundaries() and getNodes() extension methods to its Range objects.

Live demo: http://jsfiddle.net/5cdMn/

Code:

function isNodeInsideElementWithTagName(node, tagName) {
    tagName = tagName.toLowerCase();
    while (node) {
        if (node.nodeType == 1 && node.tagName.toLowerCase() == tagName) {
            returntrue;
        }
        node = node.parentNode;
    }
    returnfalse;
}

function wrapSelection(tagName) {
    varrange, textNode, i, len, j, jLen, el;
    var ranges = rangy.getSelection().getAllRanges();
    for (i = 0, len = ranges.length; i < len; ++i) {
        range = ranges[i];
        range.splitBoundaries();
        textNodes = range.getNodes([3]/* Array of node types to retrieve */);
        for (j = 0, jLen = textNodes.length; j < jLen; ++j) {
            textNode = textNodes[j];
            if (!isNodeInsideElementWithTagName(textNode, tagName)) {
                el = document.createElement(tagName);
                textNode.parentNode.insertBefore(el, textNode);
                el.appendChild(textNode);
            }
        }
    }
}

Post a Comment for "Weird Behavour Wysiwyg?"