I have a div which has some long text
For e.g. "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua."
I just want to change the color of "sit amet" upon selection through colorpicker(using colpicker.js for the color palette).
Currently what I have is:
Html code:
<div id="editor">Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.</div>
Script:
$('#editor').css('color', '#'+hex);
But the above code sets the color of the whole div content to the color set. I just want to change the color of the highlighted text.
You need to wrap selected text into some wrapepr, and unwrap it when unselected. Here is working example:
function selectText(hexColor) {
var selection = window.getSelection().getRangeAt(0);
var selectedText = selection.extractContents();
var span = document.createElement('span');
span.style.backgroundColor = hexColor;
span.className = 'selected-text';
span.appendChild(selectedText);
selection.insertNode(span);
}
function unselectText(){
$('#text-box').find('.selected-text').contents().unwrap();;
}
$(document).on('mouseup', function () {
selectText('#f90');
});
$(document).on('mousedown', function () {
unselectText();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div id="text-box">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. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.
</div>
Run code snippet to view it in action