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);
The colour of selected text can be easily changed by using the CSS | ::selection Selector. In the below code, we have used CSS ::selection on <h1> and <p> element and set its colour as yellow with green background.
Use HTML DOM Style backgroundColor Property to change the background color after clicking the button. This property is used to set the background-color of an element.
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>
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>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With