html contentEditable document.execCommand change selected opacity

abduIntegral picture abduIntegral · Dec 12, 2014 · Viewed 7.7k times · Source

any one worked with changing opacity on contentEditable selected.

I tried with following:

document.execCommand('foreColor', false, 'rgba(0,0,0,0.5)'); // with rgba
document.execCommand('foreColor', false, '80000000'); // with alpha hex

none worked. but i can easily change colour with:

document.execCommand('foreColor', false, '000000');

Can anyone help me on change opacity with document.execCommand ?

Update

On further searching found out:

document.execCommand 'foreColor' add font tag to selected with given colour. But sadly the color attribute of is not supported in HTML5.

is thats the problem ? what is its alternative ?

Answer

Abhitalks picture Abhitalks · Dec 12, 2014

You will have to use the styleWithCSS command, which specifies whether CSS or HTML formatting should be generated by the execCommand method into the document.

Refer the specs here: https://dvcs.w3.org/hg/editing/raw-file/tip/editing.html#the-stylewithcss-command .

So, in this case pass true to use the CSS styling instead of generating the font tag.

Snippet:

function setColor() {
    document.execCommand('styleWithCSS', false, true);
    document.execCommand('foreColor', false, "rgba(0,0,0,0.5)");
}
<p contentEditable="true" onmouseup="setColor();">this is some text</p>

This will generate HTML with CSS applied, like this:

<p contenteditable="true" onmouseup="setColor();">
    this is <span style="color: rgba(0, 0, 0, 0.498039);">some</span> text
</p>

Hope that helps.

.