I am trying to implement a feature when users select a text user can change the color of text using the color picker and that change should be permanent until he/she again selects the text changes the color. I am able to change the color of the whole text but not able to figure out how to change select text. I checked a lot of questions on StackOverflow but I am not able to find a solution. Here is my file
var box = document.getElementById('Myelement'); let colorpicker = document.getElementById('ColorPicker1'); setInterval(() => { let color = colorpicker.value; box.style.color = color; }, 200); /* function selectText(hexColor) { var selection = window.getSelection().getRangeAt(0); var selectedText = selection.extractContents(); var span = document.createElement('span'); span.style.color = hexColor; span.className = 'selected-text'; span.appendChild(selectedText); selection.insertNode(span); } function unselectText(){ $('#Myelement').find('.selected-text').contents().unwrap(); } $(document).on('mouseup', function () { selectText('#f90'); }); $(document).on('mousedown', function () { unselectText(); }); */
<html> <head> </head> <body> <p id="Myelement" contenteditable = "true"> Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. </p> <input name="MyColorPicker" type="color" id="ColorPicker1" /> <script> </script> <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> </body> </html>
Advertisement
Answer
you were basically there except this was an input
event on the color picker
var box = document.getElementById('Myelement'); let colorpicker = document.getElementById('ColorPicker1'); colorpicker.addEventListener('input', function(e) { selObj = window.getSelection() var selection = window.getSelection().getRangeAt(0); var selectedText = selection.extractContents(); var span = document.createElement('span'); span.style.color = e.target.value; span.className = 'selected-text'; span.appendChild(selectedText); selection.insertNode(span); })
<html> <head> </head> <body> <p id="Myelement" contenteditable="true"> Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. </p> <input name="MyColorPicker" type="color" id="ColorPicker1" /> <script> </script> <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> </body> </html>