jsf-2primefacescontextmenuright-clickbacking-beans

Primefaces right click - backing bean method call


Is there a way to invoke a backing bean ajax method in JSF2/Primefaces 5.x by right clicking on an image ? There is a contextMenu component in Primefaces but it brings up a menu, which I don't want.


Solution

  • Using this jQuery code and PrimeFaces <p:remoteCommand> you can achieve this, here is simple code:

    <h:form>
            <p:graphicImage id="myImage" onmousedown="rmc(event)" library="img" name="myImage.png" class="RMC"/>
            <p:remoteCommand name="rightMouseClick" action="#{backingBean.method}" update="myImage"/>
    </h:form>
        <script>
            $(document).on("mousedown", ".RMC", function () {
                $(".RMC").each(function () {
                    this.oncontextmenu = function () {
                        return false;
                    };
                })
    
                $(".RMC").mousedown(function (e) {
                    if (e.button == 2) {
                        rightMouseClick();
                        return false;
                    }
                    return true;
                });
            });
    
            function rmc(e) {
                this.oncontextmenu = function () {
                    return false;
                };
    
                if (e.button == 2) {
                    rightMouseClick();
                    return false;
                }
                return true;
            }
        </script>
    

    It will disable right mouse menu on images with class RMC and invoke method from backing bean. If you don't want to disable the menu just remove .each() part.

    EDIT: After updating DOM element, it loses events given during $(document).ready() so you have to add onmousedown event directly in component.

    EDIT2: Changed $(document).ready(), now works for elements with RMC class even after update.