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

AnApprentice picture AnApprentice · Dec 10, 2009 · Viewed 13.3k times · Source

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!

Answer

Warrior picture Warrior · Oct 20, 2010
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>');
  }
});