Anand mohan sinha
Anand mohan sinha

Reputation: 588

JavaScript change color of already selected text

I want to change color of already selected text you can see http://jsfiddle.net/o533v4m6/ here when you select some text at that time it's selection color depends on the class "a" or "b" even though i change the class but the color of already selected text does not change it only changes if i select the text again. Here is the code

<p class="a">
Lorem ipsum dolor sit amet, consectetur adipisicing elit. Eum repellat dolores iste ut animi magnam veritatis dignissimos porro magni quam. Facere ratione nulla vel placeat saepe molestias non porro illo.
</p>

Css

p.a::selection {
    background-color: #C5979D !important;
    color: #fff;
}

p.b::selection {
    background-color: #77B28C !important;
    color: #fff;
}

javascript

setInterval(function() {
    $('p').toggleClass('a')
    $('p').toggleClass('b')
}, 1000);

Edit :-

Solution - After changing class clear the selection and select again http://jsfiddle.net/o533v4m6/1/

Upvotes: 0

Views: 189

Answers (2)

Anand mohan sinha
Anand mohan sinha

Reputation: 588

As Hugo sousa comment says - after changing the class i cleared the selection and reselected the text.

$(function() {
    $('#color').click(function() {
       $('p').toggleClass('a')
       $('p').toggleClass('b')

        // Try to clear the selection and reselect the text
        var selection = window.getSelection()
        var elements = [];
        var ranges = [];
        if (selection.rangeCount) {
            var i = selection.rangeCount
            while (i--) {
                ranges[i] = selection.getRangeAt(i).cloneRange();
            }
            selection.removeAllRanges()
            i = ranges.length;
            while (i--)
            {
                selection.addRange(ranges[i]);
            }
        }
    });
})

Upvotes: 1

Travis
Travis

Reputation: 1284

Try changing your css to:

p.a::-moz-selection { 
    background-color: #C5979D; 
    color: #ffffff;
}

p.a::selection {
    background-color: #C5979D;
    color: #ffffff;
}

and for b:

p.b::-moz-selection { 
    background-color: #77B28C; 
    color: #ffffff;
}

p.b::selection {
    background-color: #77B28C;
    color: #ffffff;
}

and that should set the selection sets to work properly.
Source

Upvotes: 0

Related Questions