tiger
tiger

Reputation: 131

How to bind a right click context menu to the right click on jQuery

I am trying to create a custom context menu when people right clicked on the body. I am not sure how to bind the menu to the right click event, and not sure how to set up a context menu. My first question is how to bind the menu to the right click event. The second question is looking for some documentation for the menu. Thank you very much for much.

My code:

$(document).ready(function() {
  // right click event
  $("body")
    .mouseup(function(e) {
      if (e.button == 2) {
        $(this).append("<span style='color:#f00;'>Mouse up.</span>");
        return false;
      }
      return true;
    })
    .mousedown(function(e) {
      if (e.button == 2) {
        rightClickMenu();
        return false;
      }
      return true;
    });
  $("body").append("<div id='div1'></div>");

  function rightClickMenu() {
    contextMenu({},
      items: {
        "edit": {
          name: "Edit",
          icon: "edit"
        },
        "cut": {
          name: "Cut",
          icon: "cut"
        },
        "copy": {
          name: "Copy",
          icon: "copy"
        },
        "paste": {
          name: "Paste",
          icon: "paste"
        },
        "delete": {
          name: "Delete",
          icon: "delete"
        }
      });
  }
}); // end ready
#div1 {
  background-color: lightgreen;
  height: 100px;
  width: 100px;
  left: 500px;
  top: 500px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js">
</script>
<div id="div1">
</div>

Upvotes: 0

Views: 1618

Answers (1)

Astaroth
Astaroth

Reputation: 11

I made a very complex solution a few months ago but just a quick snippet to show how I solved it after getting props with rightclick. First of all I made my own event using event.special

$.event.special.clickContextMenu = {
    bindType: 'mouseup',
    delegateType: 'mouseup',
    handle: function (event) {
        var $this = $(this);
        var args = arguments;
        event.stopPropagation();
        event.preventDefault();
        if (event.which === 3) {
            $(event.target).contextmenu( function() {
                if ($('#ufdContextMenu').length > 0) {
                    return false;
                } else {
                    $(event.target).ufdContextMenu({'top':event.pageY, 'left':event.pageX});
                    return false;
                }
            });
        }
    }
}

When I initialize my element who has to get a context menu I did something like this:

$(this).BuildContextMenu({'status':status, 'number':obj1.Number});
$(this).on( "clickContextMenu", function(){} );

and here the plugIn to build the Menu:

$.fn.BuildContextMenu = function (method) {
var args = arguments;
var $this = $(this);
return this.each(function () {
        if ($.fn.BuildContextMenu.methods[method]) {
            return $.fn.BuildContextMenu.methods[method].apply(this, Array.prototype.slice.call(args, 1));
        } else if (typeof method === 'object' || !method) {
            if ($this.data('BuildContextMenu')) {
                var opts = $.extend({}, $this.data('BuildContextMenu'), method);
            } else {
                var opts = $.extend({}, $.fn.BuildContextMenu.defaults, method, $this.data());
            }
        } else {
            $.error('Method "' + method + '" does not exist');
        }
        if (!$this.data('BuildContextMenu')){
            $this.data('BuildContextMenu', {})
        };
        if (opts) $.extend($this.data('BuildContextMenu'), opts);

        $this.BuildContextMenu('buildMenu');
    });
}

$.fn.BuildContextMenu.defaults = {
    status: null,
    number: null
}

$.fn.BuildContextMenu.methods = {
    buildMenu: function () {
        var $this = $(this);
        var opts =  $this.data('BuildContextMenu');
        var menu = $('<ul class="contextMenu"></ul>');
        if (opts.status.contextMenu != undefined) {
            $.each(opts.status.contextMenu, function (key, value) {
                console.log(value);
                if (value=='transfer') {

                    var item = $('<li><i class="icon i_cm_transfer">'+content0+'</i></li>').on('click', function () {
                        console.log(content0);
                    }).appendTo(menu);

                } else if (value=='call'){
                    var item = $('<li><i class="icon i_cm_call">'+content1+'</i></li>').on('click', function () {
                         $console.log(content1);
                    }).appendTo(menu)

                } else if (value=='request Transfer'){
                    var item = $('<li><i class="icon i_cm_requestTransfer">'+content2+'</i></li>').on('click', function () {
                        $console.log(content2);
                    }).appendTo(menu)

                } else if (value=='chat'){
                    var item = $('<li><i class="icon i_cm_chat">'+content3+'</i></li>').on('click', function () {
                        $console.log(content3);
                    }).appendTo(menu)

                } else if (value=='abort'){
                    var item = $('<li><i class="icon i_cm_abort">'+content4+'</i></li>').on('click', function () {
                        console.log(content4);
                    }).appendTo(menu)

                } else if (value=='pickup'){
                    var item = $('<li><i class="icon i_cm_pickup">'+$content5+'</i></li>').on('click', function () {
                        console.log(content5);
                    }).appendTo(menu)

                }               
            });
        }

        $(this).data('menu', menu);

    }
}

Here the PlugIn to show the Context-Menu:

$.fn.ufdContextMenu = function (method) {

    var args = arguments;
    var $this = $(this);
    return this.each(function () {
        if ($.fn.ufdContextMenu.methods[method]) {
            return $.fn.ufdContextMenu.methods[method].apply(this, Array.prototype.slice.call(args, 1));
        } else if (typeof method === 'object' || !method) {
            if ($this.data('ufdContextMenu')) {
                var opts = $.extend({}, $this.data('ufdContextMenu'), method);
            } else {
                var opts = $.extend({}, $.fn.ufdContextMenu.defaults, method, $this.data());
            }
        } else {
            $.error('Method "' + method + '" does not exist');
        }
        if (!$this.data('ufdContextMenu')){
            $this.data('ufdContextMenu', {})
        };
        if (opts) $.extend($this.data('ufdContextMenu'), opts);

        $this.ufdContextMenu('showMenu');
    });
};  

$.fn.ufdContextMenu.defaults = {
    menuID: 'ufdContextMenu',
    timer: 2000,
    appendTo: $(document.body),
    top: 0,
    left: 0
}

$.fn.ufdContextMenu.methods = {
    destroy: function () {
        var $this = $(this);
        var opts =  $this.data('ufdContextMenu');
        var doc = $(document.body);
        var menu = $(document.body).find('#'+opts.menuID);
        menu.off();
        menu.remove();

    },
    showMenu: function () {
        var $this = $(this);
        var opts =  $this.data('ufdContextMenu');
        var menu = $this.data('menu');
        var doc = $(document.body);

        var timeout = setTimeout(function (){
             $this.ufdContextMenu('destroy');
        }, opts.timer);

        if (menu == undefined) {
            $.error("this element don't have a context menu to show!");
            return false;
        }

        menu.attr('id', opts.menuID);   

        menu.css({
            'position': 'absolute',
            'z-index': '9999',
            'top': opts.top + 'px',
            'left': opts.left + 'px'
        });     

        menu.on("mouseleave", function(e) {
            timeout = setTimeout(function (){
                $this.ufdContextMenu('destroy');
            }, opts.timer);
        });

        menu.on("mouseenter", function(e) {
            if (timeout != null) {
                clearTimeout(timeout);
                timeout = null;
            }
        });

        doc.append(menu);       
    }
}

Hope this helps a lot.

Upvotes: 1

Related Questions