Shikha
Shikha

Reputation: 15

Change color of selected text in a div using bootstrap & color picker

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.

Upvotes: 1

Views: 4064

Answers (2)

Vitalii Del Vorobioff
Vitalii Del Vorobioff

Reputation: 524

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

Upvotes: 3

kapantzak
kapantzak

Reputation: 11750

This just selects 'sit amet' string

jQuery:

$('#editor').replace('sit amet', '<span class="col">sit amet</span>');
$('span.col').css({'color': '#' + hex});

If you want to style a string that is not fixed:

var string = 'your selected string';
$('#editor').replace(string, '<span class="col">' + string + '</span>');
$('span.col').css({'color': '#' + hex});

Upvotes: 2

Related Questions