Question

I am writing a custom plugin for redactor to insert icons (read font awesome icons). The problem is, the icon always gets inserted at the start of the content rather than at the previous cursor position.

The Icon plugin written by me:

if (!RedactorPlugins) var RedactorPlugins = {};

RedactorPlugins.icons = {
    init: function()
    {
        var icons = '  ';
        var name = 'icons';
        var $dropdown = $('<div class="redactor_dropdown redactor_dropdown_box_' + name + '" style="display: none; width: 243px;">');

        this.buttonAddSeparator();
        this.iconPickerBuilder($dropdown, name, icons);
        $(this.$toolbar).append($dropdown);
        this.buttonAdd(name, this.opts.curLang[name], $.proxy(function(btnName, $button, btnObject, e)
        {
            this.selectionSave();
            this.dropdownShow(e, btnName);
        }, this));
    },
    iconPickerBuilder: function($dropdown, name, icons)
    {
        var _self = this;
        var onSwatch = function(e)
        {
            e.preventDefault();
            _self.iconPickerSet($(this).text());
        }

        var ilist = icons.split(' ');
        var len = ilist.length;
        for (var z = 0; z < len; z++)
        {
            var icon = ilist[z];

            var $swatch = $('<i class="fa" style="margin-right: 10px">' + icon + '</i>');
            $dropdown.append($swatch);
            $swatch.on('click', onSwatch);
        }
    },
    iconPickerSet: function(c)
    {
        this.bufferSet();
        this.$editor.focus();
        this.selectionRestore();

        var node = $('<i class="fa">' + c + '</i>');
        this.insertNode(node);
        this.sync();
    }
};

Any help appreciated.

Was it helpful?

Solution

I can't test right now, but calling this.$editor.focus() might set the focus on the wrong element when restoring the selection. According to the examples, just calling this.selectionRestore() should be enough: http://imperavi.com/redactor/examples/plugin-modal/

Have you tried it without the this.$editor.focus() statement?

Another thing I take away from the example is that they don't call the this.selectionSave() from the this.buttonAdd callback, but rather when creating the modal dialog (in their case). It's really hard to tell whether the modal behaviour would be different from the dropdown behaviour, but you could try using a modal and see if that fixes your problem.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top