Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I toggle a class on selected text?

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?

like image 788
Nubby Avatar asked Oct 16 '13 11:10

Nubby


2 Answers

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/

like image 175
Exception Avatar answered Oct 16 '22 20:10

Exception


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/>');
like image 39
Rory McCrossan Avatar answered Oct 16 '22 19:10

Rory McCrossan