Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

TinyMCE - How to add a button that wraps selected text with a tag

Tags:

jquery

tinymce

I'm currently using TinyMCE and would like to add a custom button that works as follows:

  1. User highlights text in the text-editior
  2. User clicks the custom button X
  3. The text (dog walking) is wrapped with a tag (dog walking)

Any ideas on if this can be done? I've figured out how to make a custom button inject text, but not wrap text... Here is the current code:

// Add a custom button
ed.addButton('mybutton', {
    title : 'My button',
    'class' : 'MyCoolBtn',
    image : 'MyCoolBtn.png',
    onclick : function() {
        // Add you own code to execute something on click
        ed.focus();
        ed.selection.setContent('<strong>Hello world!</strong>');
    }
});

thanks!

like image 244
AnApprentice Avatar asked Dec 10 '09 03:12

AnApprentice


2 Answers

ed.addButton('mybutton', {
  title: 'My button', 
  class: 'MyCoolBtn', 
  image: 'MyCoolBtn.png', 
  onclick: function() { 
    // Add your own code to execute something on click 
    ed.focus();
    ed.selection.setContent('<tag>' + ed.selection.getContent() + '</tag>');
  }
});
like image 143
Warrior Avatar answered Nov 18 '22 01:11

Warrior


A better way to achieve this is to (1) perform a quick check to make sure the selection isn't empty, then (2) use the execCommand() method.

Using execCommand() means the action will be available to undo. @Warrior's answer uses setContent() which will not be undoable.

ed.addButton('mybutton', {
  title: 'My button', 
  class: 'MyCoolBtn', 
  image: 'MyCoolBtn.png', 
  onclick: function() { 
    ed.focus();
    var text = ed.selection.getContent({'format': 'html'});
    if(text && text.length > 0) {
      ed.execCommand('mceInsertContent', false, '<tag>'+text+'</tag>');
    }
  }
});
like image 12
cfx Avatar answered Nov 17 '22 23:11

cfx