7

I am using the following code to change the color of text but it is not working.. Can anyone help me with this? the soloution in javascript or jquery anything is fine..

         var pinktext = "#cc0099";
        document.execCommand("ForeColor", false, pinktext);
user1844039
  • 133
  • 1
  • 1
  • 8

5 Answers5

18

document.getElementById("change_color").onclick = function() {
  // Get Selection
  sel = window.getSelection();
  if (sel.rangeCount && sel.getRangeAt) {
    range = sel.getRangeAt(0);
  }
  // Set design mode to on
  document.designMode = "on";
  if (range) {
    sel.removeAllRanges();
    sel.addRange(range);
  }
  // Colorize text
  document.execCommand("ForeColor", false, "red");
  // Set design mode to off
  document.designMode = "off";
}
<span id="content" contenteditable>
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Praesent sit amet odio eu magna mattis vehicula. Duis egestas fermentum leo. Nunc eget dapibus eros, id egestas magna. Fusce non arcu non quam laoreet porttitor non non dui. Ut elit nisl, facilisis id hendrerit et, maximus at nunc. Fusce at consequat massa. Curabitur fermentum odio risus, vel egestas ligula rhoncus id. Nam pulvinar mollis consectetur. Aenean dictum ut tellus id fringilla. Maecenas rutrum ultrices leo, sed tincidunt massa tempus ac. Suspendisse potenti. Aenean eu tempus nisl. 
</span>
<br/><br/>
<button id="change_color">Change Selected Text Color</button>
Andrew.Wolphoe
  • 420
  • 5
  • 18
  • "`How to change color of the selected text...`". How does this sinppet take care of a selected text? – Teemu Jun 25 '13 at 04:16
  • 1
    sorry but i need to change color of only the selected text not the whole text in one id. – user1844039 Jun 25 '13 at 04:23
  • 2
    This is excellent! It works cross-boundary including partial selection of elements unlike all the other solutions I've seen. Any idea how to add a CSS class instead of inline CSS styling? – SharpC Mar 23 '18 at 17:59
  • @SharpC https://stackoverflow.com/questions/23380628/how-to-add-class-or-id-or-css-style-in-execcommand-formatblock-p-tag – NETCreator Hosting - WebDesign Apr 12 '18 at 04:22
  • @NETCreatorHosting-WebDesign Very good Example....Up-voted. This should have been marked as correct. – Jonny Jul 02 '18 at 22:34
  • @NETCreatorHosting-WebDesign, the code snippet works in the embedded IDE here. But I cannot run it in my localhost site. I have created a fiddle here (https://jsfiddle.net/jsf_user/dyjqw5vt/3/) where too the code does not work. – Istiaque Ahmed Jul 31 '18 at 16:31
  • @IstiaqueAhmed it is working, on my end, at the JSFiddle link too. What browser are you using? – NETCreator Hosting - WebDesign Jul 31 '18 at 18:10
  • @NETCreatorHosting-WebDesign,oh yes, it works now from another FF browser. Not sure which version I used then. BTW if I want to get the highlight only within a certain `div`, what should I do ? – Istiaque Ahmed Jul 31 '18 at 19:25
  • @NETCreatorHosting-WebDesign, from Firefix Quantum 61.0.1 (64-bit), the fiddle does not work. – Istiaque Ahmed Aug 01 '18 at 07:30
  • @IstiaqueAhmed Do you get any errors in the console? However, If you don't get any errors, I will install this browser version to check it out. – NETCreator Hosting - WebDesign Aug 01 '18 at 18:16
  • @IstiaqueAhmed you can check if the selection range is inside specified elements like this https://stackoverflow.com/questions/8339857/how-to-know-if-selected-text-is-inside-a-specific-div – NETCreator Hosting - WebDesign Aug 01 '18 at 18:20
1

The following code works when you select a text or word, the color will change:

<style>
::selection {
    color:blue;
    background:yellow;
    font-size:14px;
}

::-moz-selection {
    color:blue;
    background:yellow;
    font-size:14px;
}
</style>
Draken
  • 3,134
  • 13
  • 34
  • 54
1

Check DEMO here http://jsfiddle.net/yeyene/GYuBv/7/

Select text, and click button to change selected text color.

function selectHTML() {
    try {
        if (window.ActiveXObject) {
            var c = document.selection.createRange();
            return c.htmlText;
        }

        var nNd = document.createElement("span");
        var w = getSelection().getRangeAt(0);
        w.surroundContents(nNd);
        return nNd.innerHTML;
    } catch (e) {
        if (window.ActiveXObject) {
            return document.selection.createRange();
        } else {
            return getSelection();
        }
    }
}

$(function() {
    $('#changeColor').click( function() {
        var mytext = selectHTML();
        // you can modify any css style here...
        $('span').css({"color":"red"});
    });
});
yeyene
  • 7,297
  • 1
  • 21
  • 29
  • thanks. but in this it is changing only the background color, i want the text to change color from black to some other color. Can we do that? – user1844039 Jun 25 '13 at 05:40
  • yes, you can, just update the .css() function anything you want. See http://jsfiddle.net/yeyene/GYuBv/7/ – yeyene Jun 25 '13 at 05:49
1

Try this

mark up

<p>
I am using the following code to change the color of text but it is not working.. Can    anyone help me with this? the soloution in javascript or jquery anything is fine..
</p>

Script

<script type="text/javascript" >

   $(document).ready(function(){
       $("p").on("mouseup" , function(){
          selectedtext = selectedText();
          var replceText = "<span style='background:#cccccc' >"+selectedtext+"</span>";
          var gethtmlText = $(this).text();
          var replcedtext = gethtmlText.replace(selectedtext ,  replceText);
         $(this).html(replcedtext)
       });
 });

function selectedText(){
    if(document.getSelection){
      return document.getSelection();
    }
    else if(document.selection){
      return document.selection.createRange().text;
    }
}

</script>
Shinov T
  • 862
  • 5
  • 9
  • Awesome!!! If some one needs to update only selected text html not the whole text then follow this code it's just a single tweak of above code **var gethtmlText = $(this).html();** – Tamaghna Banerjee Feb 07 '17 at 17:45
0

I've created a pretty short fiddle that demonstrates the use of jQuery to change the color of a piece of text.

HTML:

<p id="paragraph">Sed ut perspiciatis unde omnis iste natus error sit voluptatem accusantium doloremque laudantium?</p>
<button id="colorChanger">This Button changes the text color of the paragraph.</button>

CSS:

#paragraph {
    color: green;
}

JavaScript:

$('#colorChanger').click(function() {
    $('#paragraph').css('color','black');
});

The code above shows that with any text you can change the color using jQuery's css method. Additionally, I used #paragraph to access the paragraph; however, you can use nth-child through jQuery, you can cycle through the children of a container using a loop and checking for the right one then using the css method from jQuery. These are just a few of the ways to change the color of a piece of text.

Ilan Biala
  • 3,319
  • 5
  • 36
  • 45