Make Selected Text Bold Using Javascript
I have a text in my markup:
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Vestibulum condimentum consectetur tellus, at bibendum felis ultrices eu. Nullam ni
Solution 1:
Perhaps this can help you: http://code.google.com/p/rangy/
one of the examples is exactly what you're after.
Solution 2:
You could use document.execCommand()
for this. Here's my answer to a similar question: Javascript: how to un-surroundContents range
Solution 3:
This works (in Chrome), but so long as it's only called once!
(running code at http://jsfiddle.net/HaD6k/)
$(document).keypress(function(e) {
if (e.which == 13 && e.ctrlKey) {
var s = getSelection();
var i = s.baseOffset;
var j = s.extentOffset;
var t = $('div').text();
var t0 = t.substring(0, i) + '<span class="b">' +
t.substring(i, j) + '</span>' +
t.substring(j);
$('div').html(t0);
}
});
The reason it only works once is because it modifies the DOM to add the tags, which means next time around the selection offsets and elements aren't contiguous. I'm still looking at that...
Post a Comment for "Make Selected Text Bold Using Javascript"