Search code examples
jquerycontextmenujhtmlarea

How to add context menu to jHtmlArea


I need to add a jquery contextMenu to the jHtmlArea so it can add keywords into the jHtmlArea, but i am having difficulty passing the iframe tag to the contextMenu trigger.

Here the code

$(function () {

    $.contextMenu({
        selector: 'iframe body', 
        className: 'data-title',
        callback: function (key, options) {
            //inserts the keyword selected
            insertAtCaret($(this).attr('id'), '{' + key + '}');
        },
        items: {
            "TestPath": { name: "Test path", icon: "" },
           ...
        }
    });

    //adding an extra button to the jHtmlArea
    jHtmlArea.defaultOptions.toolbar.push([
        {
            // This is how to add a completely custom Toolbar Button
            css: "keywords",
            text: "Insert keywords",
            action: function (btn) {
                this.contextMenu(); //Error:this.contextMenu is not a function
            }
        }
    ]);

    //just for context...
    function insertAtCaret(areaId, text) {
       ...
    }

   //setting up `jHtmlArea` for input #editor

   $('#editor').htmlarea();

});

I try many ways to get the 'iframe body' element with no success when click on the custom toolbar button. Also i try to move the contextMenu creation to inside the jHtml load event, hopping the problem was that the iframe loads after document ready.

Other approach that could work was to simply specify the selector 'iframe' for the context menu and then menu should pop when the user right click inside the frame.

I need some guidelines or a different approach.


Solution

  • I manage to pop the contextMenu from the Toolbar button. I am pretty sure that there is a way to pop from inside the iframe but i can't find it. Here my solution:

    jHtmlArea.defaultOptions.toolbar.push([
    {
        // This is how to add a completely custom Toolbar Button
        css: "keywords",
        text: "Insert keywords",
        action: function (btn) {
    
            var jhtml = this;
            $(function () {
    
                $.contextMenu({
                    selector: '.keywords',
                    className: 'data-title',
                    callback: function (key, options) {
                        jhtml.pasteHTML("{" +key+ "}");
                    },
                    items: {
                        "WorkerUnit": { name: "Worker Unit", icon: "" },
                        ...
                    }
                });
    
                $('.keywords').contextMenu(); //call it
            });
        }
    }
    ]);