5

I'm trying to create a fairly simple text editor (bold, italic, indent) and need to be able to toggle the class associated with the button on click. I have this code:

var selected = function ()
{
  var text = '';
  if (window.getSelection) {
    text = window.getSelection();
  }
  return text;
}

$('textarea').select(function(eventObject)
{
  console.log(selected().toString());
  var selectedtext = selected().toString();
    $('#bold-button').click(function () { 
      $(selectedtext).addClass('bold-text');
    });
});

And I can get the selected text to print, but can't get the class added. I've seen other solutions that add the class on click to the entire textarea, but I dont need that. Any help?

Nubby
  • 157
  • 2
  • 13

2 Answers2

4

You could use surroundContents() like below. Before demo here http://jsfiddle.net/jwRG8/3/

    function surroundSelection() {
        var span = document.createElement("span");
        span.style.fontWeight = "bold";
        span.style.color = "green";

        if (window.getSelection) {
            var sel = window.getSelection();
            if (sel.rangeCount) {
                var range = sel.getRangeAt(0).cloneRange();
                range.surroundContents(span);
                sel.removeAllRanges();
                sel.addRange(range);
            }
        }
    }

But this is not supported less than IE9. And I worked on text selections before and I found them in consistent. Tim Down is very much experienced on selections and most of the answers in SO related to Selections are given my him. He has written a plugin called rangy. You mat try it at https://code.google.com/p/rangy/

Community
  • 1
  • 1
Exception
  • 8,111
  • 22
  • 85
  • 136
  • This doesn't seem to work within the textarea. I guess I'll have to use tag wrapping instead of actually changing the text – Nubby Oct 16 '13 at 11:38
2

Because you are selecting text directly, there is no element to add the class on. textNodes cannot have classes. Instead, try wrapping the text in an element:

$('textarea').select(function(eventObject) {
    console.log(selected().toString());
    var selectedtext = selected().toString();
    $(selectedtext).wrap('<span />').parent().addClass('bold-text');
})

Or you could just wrap it in a b tag, without the class:

$(selectedtext).wrap('<b/>');
Rory McCrossan
  • 331,213
  • 40
  • 305
  • 339