I’m developing a plugin for context menu of different divs
<div>
<div class='first'>some data</div>
<div class='second'>some data</div>
<div class='third'>some data</div>
<div class='fourth'>some data</div>
</div>
This is the menu to display as context menu:
<ul id='cmenu'>
<li id='menuItem1'>Item1</li>
<li id='menuItem2'>Item1</li>
<li id='menuItem3'>Item1</li>
<li id='menuItem4'>Item1</li>
<li id='menuItem5'>Item1</li>
<li id='menuItem6'>Item1</li>
</ul>
How this plugin works: it changes the list of menu items for every division and the callbacks for menu items are also changed.
(function($) {
$.fn.cnxtmenu = function(options) {
var defaults = {
'menuid' : '',
item1 : function() {},
item2 : function() {},
item3 : function() {},
item4 : function() {},
item5 : function() {},
item6 : function() {},
},
opt = $.extend({}, defaults, options);
var mid = '#'+opt.menuid, seldiv;
this.live({
"contextmenu" : function(e) {
seldiv = $(this);
if ($(this).hasClass('first')) {
//change the menu list
}
else if($(this).hasClass('second')){
// change the menu list to display different items
}
else if($(this).hasClass('file-list')){
//differ list
}
else if($(this).hasClass('dstore_file-list')){
//differ menu list
}
$(mid).css({
top : e.pageY + 'px',
left : e.pageX + 'px'
}).show();
return false;
}
});
$(mid).children('li').unbind('click').click(function(e) {
e.stopPropagation();
e.preventDefault();
switch(this.id) {
case 'menuItem1':
opt.item1(this, seldiv);
break;
case 'menuItem2':
opt.item2(this, seldiv);
break;
case 'menuItem3':
opt.item3(this, seldiv);
break;
case 'menuItem4':
opt.item4(this, seldiv);
break;
case 'menuItem5':
opt.item5(this, seldiv);
break;
case 'menuItem6':
opt.item6(this, seldiv);
break;
}
$(mid).hide();
return false;
});
$(mid).click(function() {
$(mid).hide();
});
$(document).click(function() {
$(mid).hide();
});
}
})(jQuery);
and I am using this plugin like this.
$('.first').cnxtmenu({menuid:'cmenu',
item1:some callbacks
});
//...
$('.fourth').cnxtmenu({menuid:'cmenu',
// soem differt callbacks.
});
For all the four div are assigned different callbacks.
My problem is that callbacks are not differing for the selectors, the only last i.e. fourth selector’s callbacks are executing. And callbacks are triggering many times.
Help me what’s wrong in my code please.
Thanks in advance.
I got your problem you are assigning callbacks in wrong way. and the callbacks are assigning as you specified for last division. So you need to assign the callbacks inside the contextmenu function.
second as many times you call the plugin, the plugin code will also execute and as your code the callbacks are also assign at the onload. no need to worry after the code change.