Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to enable/disable custom button on selection change with tinymce

I use this code to create a custom tinymce button that changes a class of image. It's in the setup block.

ed.addButton('cust_setimgaspreview', {
        title : 'Set image as a preview image',
        image : 'ikony/previews.png',
        onclick : function() {
            if(ed.selection.getNode().tagName == 'IMG')
            {
                 ed.selection.getNode().className = 'preview';
            } else {
                alert('You need to select an image.');
            }
        }
    });

As you can see, I use an "ugly approach" to disable the class change on other elements than image. How can I disable/enable the button in the same way as tinymce does with its default buttons (like edit image or edit link)? I guess I need to somehow catch selection change and then change the button state depending on the selection, but I have no ide how to do that.

like image 474
Amunak Avatar asked Jul 24 '12 12:07

Amunak


1 Answers

Just figured it out - it's quite simple. I've just edited my setup function and added "onNodeChange" handler.

setup : function(ed) {

    ed.onNodeChange.add(function(ed, cm, node) {
        cm.setDisabled('cust_setimgaspreview', !(node.tagName == 'IMG'))
    });

    ed.addButton('cust_setimgaspreview', {
        title : 'Set image as a preview image',
        image : 'ikony/previews.png',
        onclick : function() {
            ed.selection.getNode().className = 'preview';
        }
    });

}
like image 73
Amunak Avatar answered Nov 14 '22 23:11

Amunak