I developed a simple jQuery plugin that works fine when I right click on a div, but when I click on a second div the context menu appears on the first div. Here's the jsfiddle. What's wrong with this plugin?
The plugin code:
(function ( $ ) {
var menu = null;
$.fn.ctxMenu = function( options ) {
var settings = $.extend({
menuItems: null,
onclick: null
}, options );
show(this,settings.menuItems,settings.onclick);
};
function show(obj,menuItems,onclick){
obj.bind( "contextmenu", function(e) {
if (e.preventDefault) e.preventDefault();
if (e.stopPropagation) e.stopPropagation();
render(obj,e.offsetX, e.offsetY,menuItems,onclick);
});
obj.bind( "click", function(e) {
if (menu != null)
menu.remove();
});
}
function render(obj,x,y,menuItems,onclick) {
if (menu != null)
menu.remove();
menu = $('<div id="menu" class="ctxMenu" />');
obj.append(menu);
menu.css('padding-top', '4px' );
menu.css('padding-bottom', '0px' );
menu.css('padding-left', '6px' );
menu.css('padding-right', '20px' );
menu.css('position', 'absolute' );
menu.css('top', y+'px' );
menu.css('left', x+'px' );
for (var i=0;i<menuItems.length;i++) {
var item = $('<div id="item" style="height:20px;padding:2px;cursor:default;" />');
item.attr('opt',menuItems[i].opt);
var p = $('<p id="p' + i + '" style="margin:0" />' );
p.text(menuItems[i].optCaption);
p.attr('opt',menuItems[i].opt);
item.append(p);
menu.append(item);
item.bind( "click", function(e) {
if (typeof onclick == 'function')
onclick.call(this,obj.attr('id'),$(e.target).attr('opt'));
});
}
}
}( jQuery ));
And sample code of how to invoke it:
$div.ctxMenu({
menuItems: [ { opt:1, optCaption: "Option 1" },
{ opt:2, optCaption: "Option 2" },
{ opt:3, optCaption: "Option 3" }
],
change: function(id,opt) {
alert(id+"-"+opt);
}
});
position:relativeon the parent container: jsfiddle.net/pevans02/dzSRR/7position:relativeon the two divs you dynamically create