-1

I am trying to use jquery colorpicker to change text color of the selected text from a div.Here is my code

var colorpickerOptions = {

  select: function (event, color) {
    var color_in_hex_format = color.formatted;
    document.execCommand('foreColor', false, '#'+color_in_hex_format);
    $('.colorpicker').css('background-color','#'+color_in_hex_format);
}    

,inline: false
};

$('.colorpicker').colorpicker(colorpickerOptions);

But document.execCommand('foreColor', false, '#'+color_in_hex_format); was not working when i choose a color from colorpicker.Why?

Here is the demo code FIDDLE

Shijin TR
  • 7,516
  • 10
  • 55
  • 122

2 Answers2

3

You can wrap the selected text with a span element and add color to that span, you'll need to save the selected code on mouseup on the div, then use .html() to wrap text with span.

Get selected text code code from TimDown

function getSelectionHtml() {
    var html = "";
    if (typeof window.getSelection != "undefined") {
        var sel = window.getSelection();
        if (sel.rangeCount) {
            var container = document.createElement("div");
            for (var i = 0, len = sel.rangeCount; i < len; ++i) {
                container.appendChild(sel.getRangeAt(i).cloneContents());
            }
            html = container.innerHTML;
        }
    } else if (typeof document.selection != "undefined") {
        if (document.selection.type == "Text") {
            html = document.selection.createRange().htmlText;
        }
    }
    return html;
}

Save selected text on mouse up

var selection = "";
$('[contenteditable]').on('mouseup',function(){
selection = getSelectionHtml();

});

Wrap text with a span

    $('[contenteditable]').html(function(){
        return this.textContent.replace(selection,'<span style="color:#'+color_in_hex_format+'">'+selection+'</span>');
    });

DEMO

Another version

If you want to change color of more than one selection you can change the html like this

    $('[contenteditable]').html(html.replace(selection,'<span style="color:#'+color_in_hex_format+'">'+selection+'</span>'));

DEMO

Community
  • 1
  • 1
Anton
  • 32,245
  • 5
  • 44
  • 54
  • have you tried changing the text color at least 2 times? The first time it works OK, try selecting another text, then only the recent selected text has color affected, the last selected text becomes normal. – King King May 13 '14 at 13:56
  • Yeah, i guess i was hoping that was the expected solution, but i could add a way doing it more than once @KingKing – Anton May 13 '14 at 14:02
  • +1 for the updated demo, however it's not such simple, try selecting a new text which covering both already colored text, it won't work then. I think it's the most complicated case related to this problem. – King King May 13 '14 at 14:07
  • @KingKing Do you mean select a text which already has a color? **edit:** ah just noticed that it doesn't create a span on click, it does onchange in the color picker so there are multiple spans for a selected text – Anton May 13 '14 at 14:08
  • not really, I mean the text you select should **cover** at least 2 other text which have already been colored (such as by `red` and `green`), the new text should be colored as `blue` but it won't work. – King King May 13 '14 at 14:10
  • another problem is if you select some text containing a word/phrase such as `the` to color, then after that text, you select **only** the text which is **exactly** `the`, then the first `the` (in the firstly colored text) will be affected by the new color, while the lately selected word `the` won't be affected. – King King May 13 '14 at 14:13
  • @KingKing Ah yeah i see :/ i'll see if i could figure something out. – Anton May 13 '14 at 14:15
1

As per mozilla documentation about execCommands:

foreColor:
Changes a font color for the selection or at the insertion point. This requires a color value string to be passed in as a value argument.

So in your code, even if you select anything from the contenteditable, once you click on colorpicker button, your selection is lost so your execCommand doesn't work. You can check for the selected text using console and it shows that no text is selected.

Here is the code test:

var colorpickerOptions = {
select: function (event, color) {
    var color_in_hex_format = color.formatted;
    console.log(window.getSelection().toString());//Checks for selected text
    //document.execCommand('foreColor', false, '#'+color_in_hex_format);
    $('[contenteditable]').css('color', '#' + color_in_hex_format);
    $('.colorpicker').css('background-color', '#' + color_in_hex_format);
},inline: false
};
$('.colorpicker').colorpicker(colorpickerOptions);

So, the simple solution will be to either apply the color css to complete div like:

$('[contenteditable]').css('color', '#' + color_in_hex_format);

by replacing the execCommand line with the above line. Demo : http://jsfiddle.net/lotusgodkk/6V7hL/144/

PS: I didn't downvote your question.

K K
  • 17,794
  • 4
  • 30
  • 39