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

javascript, tinymce, wysiwyg

Solution

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';
        }
    });

}

Problem

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.

Original source

Related problems