The following code is supposed to surround the highlighted text in a given Div with a span.
$(document).ready(function(){
$('.format').click(function(){
var highlight = window.getSelection();
var spn = '<span class="highlight">' + highlight + '</span>';
$('.conttext').content().replace(highlight, spn);
});
});
A function of this nature could be used to provide formating options to an HTML contenteditable DIV.
Something is clearly wrong though as it does not currently work.
http://jsfiddle.net/BGKSN/20/
DEMO: http://jsfiddle.net/BGKSN/24/
$(document).ready(function(){
$('.format').click(function(){
var highlight = window.getSelection();
var spn = '<span class="highlight">' + highlight + '</span>';
var text = $('.conttext').text();
$('.conttext').html(text.replace(highlight, spn));
});
});
Later Edit:
Based on the comment, this is the real functional example:
http://jsfiddle.net/BGKSN/40/
$(document).ready(function(){
$('.format').click(function(){
var highlight = window.getSelection(),
spn = '<span class="highlight">' + highlight + '</span>',
text = $('.conttext').text(),
range = highlight.getRangeAt(0),
startText = text.substring(0, range.startOffset),
endText = text.substring(range.endOffset, text.length);
$('.conttext').html(startText + spn + endText);
});
});
Docs: https://developer.mozilla.org/en-US/docs/Web/API/window.getSelection
Well, first off, you had your html wrong, something like this
<a href="" class="format">test</div>
Secondly, when you tried to click test it deselected the selected text because this is what happens if you click somewhere when you have some text selected. So, with this in mind, I changed it to $("body").keypress()
so it will wrap the highlighted text in span when a key is pressed. Also, fixed some of the jQuery code and voila, it works!
Check it out here.
If you fix your anchor tag and your jQuery a bit
$(".contenttext").contents()
where .contents()
is a non-existand function to
$(".contenttext").html($(".contenttext").html().replace(highlight, spn));
it works as expected as seen here.