Question

I am making a text editor, however the remove underline functionality won't work. working code example: jsfiddle

Here is the code that gives the problem

else if (tag == "u") {
    sell = window.getSelection().getRangeAt(0);

    if (selectionIsUnderlined()) {
        node = range.createContextualFragment("<font style='text-decoration: none !important'>" + sell + "</font>");
    } else {
        node = range.createContextualFragment("<u>" + sell + "</u>");
    }

    range.deleteContents();
}

any ideas?

Was it helpful?

Solution

Well the issues with removing underline was that the selection did not take into account the wrapping <u> element. The content inside <u> was removed and new content with <font> tag inserted inside <u> tag.

I tried to go up one node and check if it is <u> and then remove the node:

if (selectionIsUnderlined()) {
    node = range.createContextualFragment(
           "<font style='text-decoration: none !important'>" + sell + "</font>");
    var nd = sel.anchorNode;
    if(nd.nodeName!=='span'){
        nd = nd.parentNode;
    }

    if (nd) {
        nd.remove();
    }

The updated fiddle is here

PS:- this is just an experiment. please consider performance/browser compatibility and other pros/cons before using it.

OTHER TIPS

Try something like this:

var node="";
var divs=0;

if (selectionIsUnderlined()) {
   node+="<div class=underline>";
   divs++;
}

if(selectionIsBold()){
   node+="<div class=bold>";
   divs++;
}

node+=sell;

Then close your divs.

.underline{
   text-decoration: underline;
}

etc..

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top