jquery.contextmenu.js 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266
  1. /**
  2. * Copyright (c)2005-2009 Matt Kruse (javascripttoolbox.com)
  3. *
  4. * Dual licensed under the MIT and GPL licenses.
  5. * This basically means you can use this code however you want for
  6. * free, but don't claim to have written it yourself!
  7. * Donations always accepted: http://www.JavascriptToolbox.com/donate/
  8. *
  9. * Please do not link to the .js files on javascripttoolbox.com from
  10. * your site. Copy the files locally to your server instead.
  11. *
  12. */
  13. /**
  14. * jquery.contextmenu.js
  15. * jQuery Plugin for Context Menus
  16. * http://www.JavascriptToolbox.com/lib/contextmenu/
  17. *
  18. * Copyright (c) 2008 Matt Kruse (javascripttoolbox.com)
  19. * Dual licensed under the MIT and GPL licenses.
  20. *
  21. * @version 1.1
  22. * @history 1.1 2010-01-25 Fixed a problem with 1.4 which caused undesired show/hide animations
  23. * @history 1.0 2008-10-20 Initial Release
  24. * @todo slideUp doesn't work in IE - because of iframe?
  25. * @todo Hide all other menus when contextmenu is shown?
  26. * @todo More themes
  27. * @todo Nested context menus
  28. */
  29. var $J = jQuery.noConflict();
  30. ;(function($J){
  31. $J.contextMenu = {
  32. shadow:true,
  33. shadowOffset:0,
  34. shadowOffsetX:5,
  35. shadowOffsetY:5,
  36. shadowWidthAdjust:-3,
  37. shadowHeightAdjust:-3,
  38. shadowOpacity:.2,
  39. shadowClass:'context-menu-shadow',
  40. shadowColor:'black',
  41. offsetX:0,
  42. offsetY:0,
  43. appendTo:'body',
  44. direction:'down',
  45. constrainToScreen:true,
  46. showTransition:'show',
  47. hideTransition:'hide',
  48. showSpeed:null,
  49. hideSpeed:null,
  50. showCallback:null,
  51. hideCallback:null,
  52. className:'context-menu',
  53. itemClassName:'context-menu-item',
  54. itemHoverClassName:'context-menu-item-hover',
  55. disabledItemClassName:'context-menu-item-disabled',
  56. disabledItemHoverClassName:'context-menu-item-disabled-hover',
  57. separatorClassName:'context-menu-separator',
  58. innerDivClassName:'context-menu-item-inner',
  59. themePrefix:'context-menu-theme-',
  60. theme:'default',
  61. separator:'context-menu-separator', // A specific key to identify a separator
  62. target:null, // The target of the context click, to be populated when triggered
  63. menu:null, // The jQuery object containing the HTML object that is the menu itself
  64. shadowObj:null, // Shadow object
  65. bgiframe:null, // The iframe object for IE6
  66. shown:false, // Currently being shown?
  67. useIframe:/*@cc_on @*//*@if (@_win32) true, @else @*/false,/*@end @*/ // This is a better check than looking at userAgent!
  68. // Create the menu instance
  69. create: function(menu,opts) {
  70. var cmenu = $J.extend({},this,opts); // Clone all default properties to created object
  71. // If a selector has been passed in, then use that as the menu
  72. if (typeof menu=="string") {
  73. cmenu.menu = $J(menu);
  74. }
  75. // If a function has been passed in, call it each time the menu is shown to create the menu
  76. else if (typeof menu=="function") {
  77. cmenu.menuFunction = menu;
  78. }
  79. // Otherwise parse the Array passed in
  80. else {
  81. cmenu.menu = cmenu.createMenu(menu,cmenu);
  82. }
  83. if (cmenu.menu) {
  84. cmenu.menu.css({display:'none'});
  85. $J(cmenu.appendTo).append(cmenu.menu);
  86. }
  87. // Create the shadow object if shadow is enabled
  88. if (cmenu.shadow) {
  89. cmenu.createShadow(cmenu); // Extracted to method for extensibility
  90. if (cmenu.shadowOffset) { cmenu.shadowOffsetX = cmenu.shadowOffsetY = cmenu.shadowOffset; }
  91. }
  92. $J('body').bind('contextmenu',function(){cmenu.hide();}); // If right-clicked somewhere else in the document, hide this menu
  93. return cmenu;
  94. },
  95. // Create an iframe object to go behind the menu
  96. createIframe: function() {
  97. return $J('<iframe frameborder="0" tabindex="-1" src="javascript:false" style="display:block;position:absolute;z-index:-1;filter:Alpha(Opacity=0);"/>');
  98. },
  99. // Accept an Array representing a menu structure and turn it into HTML
  100. createMenu: function(menu,cmenu) {
  101. var className = cmenu.className;
  102. $J.each(cmenu.theme.split(","),function(i,n){className+=' '+cmenu.themePrefix+n});
  103. var $Jt = $J('<table cellspacing=0 cellpadding=0></table>').click(function(){cmenu.hide(); return false;}); // We wrap a table around it so width can be flexible
  104. var $Jtr = $J('<tr></tr>');
  105. var $Jtd = $J('<td></td>');
  106. var $Jdiv = $J('<div class="'+className+'"></div>');
  107. // Each menu item is specified as either:
  108. // title:function
  109. // or title: { property:value ... }
  110. for (var i=0; i<menu.length; i++) {
  111. var m = menu[i];
  112. if (m==$J.contextMenu.separator) {
  113. $Jdiv.append(cmenu.createSeparator());
  114. }
  115. else {
  116. for (var opt in menu[i]) {
  117. $Jdiv.append(cmenu.createMenuItem(opt,menu[i][opt])); // Extracted to method for extensibility
  118. }
  119. }
  120. }
  121. if ( cmenu.useIframe ) {
  122. $Jtd.append(cmenu.createIframe());
  123. }
  124. $Jt.append($Jtr.append($Jtd.append($Jdiv)))
  125. return $Jt;
  126. },
  127. // Create an individual menu item
  128. createMenuItem: function(label,obj) {
  129. var cmenu = this;
  130. if (typeof obj=="function") { obj={onclick:obj}; } // If passed a simple function, turn it into a property of an object
  131. // Default properties, extended in case properties are passed
  132. var o = $J.extend({
  133. onclick:function() { },
  134. className:'',
  135. hoverClassName:cmenu.itemHoverClassName,
  136. icon:'',
  137. disabled:false,
  138. title:'',
  139. hoverItem:cmenu.hoverItem,
  140. hoverItemOut:cmenu.hoverItemOut
  141. },obj);
  142. // If an icon is specified, hard-code the background-image style. Themes that don't show images should take this into account in their CSS
  143. var iconStyle = (o.icon)?'background-image:url('+o.icon+');':'';
  144. var $Jdiv = $J('<div class="'+cmenu.itemClassName+' '+o.className+((o.disabled)?' '+cmenu.disabledItemClassName:'')+'" title="'+o.title+'"></div>')
  145. // If the item is disabled, don't do anything when it is clicked
  146. .click(function(e){if(cmenu.isItemDisabled(this)){return false;}else{return o.onclick.call(cmenu.target,this,cmenu,e)}})
  147. // Change the class of the item when hovered over
  148. .hover( function(){ o.hoverItem.call(this,(cmenu.isItemDisabled(this))?cmenu.disabledItemHoverClassName:o.hoverClassName); }
  149. ,function(){ o.hoverItemOut.call(this,(cmenu.isItemDisabled(this))?cmenu.disabledItemHoverClassName:o.hoverClassName); }
  150. );
  151. var $Jidiv = $J('<div class="'+cmenu.innerDivClassName+'" style="'+iconStyle+'">'+label+'</div>');
  152. $Jdiv.append($Jidiv);
  153. return $Jdiv;
  154. },
  155. // Create a separator row
  156. createSeparator: function() {
  157. return $J('<div class="'+this.separatorClassName+'"></div>');
  158. },
  159. // Determine if an individual item is currently disabled. This is called each time the item is hovered or clicked because the disabled status may change at any time
  160. isItemDisabled: function(item) { return $J(item).is('.'+this.disabledItemClassName); },
  161. // Functions to fire on hover. Extracted to methods for extensibility
  162. hoverItem: function(c) { $J(this).addClass(c); },
  163. hoverItemOut: function(c) { $J(this).removeClass(c); },
  164. // Create the shadow object
  165. createShadow: function(cmenu) {
  166. cmenu.shadowObj = $J('<div class="'+cmenu.shadowClass+'"></div>').css( {display:'none',position:"absolute", zIndex:9998, opacity:cmenu.shadowOpacity, backgroundColor:cmenu.shadowColor } );
  167. $J(cmenu.appendTo).append(cmenu.shadowObj);
  168. },
  169. // Display the shadow object, given the position of the menu itself
  170. showShadow: function(x,y,e) {
  171. var cmenu = this;
  172. if (cmenu.shadow) {
  173. cmenu.shadowObj.css( {
  174. width:(cmenu.menu.width()+cmenu.shadowWidthAdjust)+"px",
  175. height:(cmenu.menu.height()+cmenu.shadowHeightAdjust)+"px",
  176. top:(y+cmenu.shadowOffsetY)+"px",
  177. left:(x+cmenu.shadowOffsetX)+"px"
  178. }).addClass(cmenu.shadowClass)[cmenu.showTransition](cmenu.showSpeed);
  179. }
  180. },
  181. // A hook to call before the menu is shown, in case special processing needs to be done.
  182. // Return false to cancel the default show operation
  183. beforeShow: function() { return true; },
  184. // Show the context menu
  185. show: function(t,e) {
  186. var cmenu=this, x=e.pageX, y=e.pageY;
  187. cmenu.target = t; // Preserve the object that triggered this context menu so menu item click methods can see it
  188. if (cmenu.beforeShow()!==false) {
  189. // If the menu content is a function, call it to populate the menu each time it is displayed
  190. if (cmenu.menuFunction) {
  191. if (cmenu.menu) { $J(cmenu.menu).remove(); }
  192. cmenu.menu = cmenu.createMenu(cmenu.menuFunction(cmenu,t),cmenu);
  193. cmenu.menu.css({display:'none'});
  194. $J(cmenu.appendTo).append(cmenu.menu);
  195. }
  196. var $Jc = cmenu.menu;
  197. x+=cmenu.offsetX; y+=cmenu.offsetY;
  198. var pos = cmenu.getPosition(x,y,cmenu,e); // Extracted to method for extensibility
  199. cmenu.showShadow(pos.x,pos.y,e);
  200. // Resize the iframe if needed
  201. if (cmenu.useIframe) {
  202. $Jc.find('iframe').css({width:$Jc.width()+cmenu.shadowOffsetX+cmenu.shadowWidthAdjust,height:$Jc.height()+cmenu.shadowOffsetY+cmenu.shadowHeightAdjust});
  203. }
  204. $Jc.css( {top:pos.y+"px", left:pos.x+"px", position:"absolute",zIndex:9999} )[cmenu.showTransition](cmenu.showSpeed,((cmenu.showCallback)?function(){cmenu.showCallback.call(cmenu);}:null));
  205. cmenu.shown=true;
  206. $J(document).one('click',null,function(){cmenu.hide()}); // Handle a single click to the document to hide the menu
  207. }
  208. },
  209. // Find the position where the menu should appear, given an x,y of the click event
  210. getPosition: function(clickX,clickY,cmenu,e) {
  211. var x = clickX+cmenu.offsetX;
  212. var y = clickY+cmenu.offsetY
  213. var h = $J(cmenu.menu).height();
  214. var w = $J(cmenu.menu).width();
  215. var dir = cmenu.direction;
  216. if (cmenu.constrainToScreen) {
  217. var $Jw = $J(window);
  218. var wh = $Jw.height();
  219. var ww = $Jw.width();
  220. if (dir=="down" && (y+h-$Jw.scrollTop() > wh)) { dir = "up"; }
  221. var maxRight = x+w-$Jw.scrollLeft();
  222. if (maxRight > ww) { x -= (maxRight-ww); }
  223. }
  224. if (dir=="up") { y -= h; }
  225. return {'x':x,'y':y};
  226. },
  227. // Hide the menu, of course
  228. hide: function() {
  229. var cmenu=this;
  230. if (cmenu.shown) {
  231. if (cmenu.iframe) { $J(cmenu.iframe).hide(); }
  232. if (cmenu.menu) { cmenu.menu[cmenu.hideTransition](cmenu.hideSpeed,((cmenu.hideCallback)?function(){cmenu.hideCallback.call(cmenu);}:null)); }
  233. if (cmenu.shadow) { cmenu.shadowObj[cmenu.hideTransition](cmenu.hideSpeed); }
  234. }
  235. cmenu.shown = false;
  236. }
  237. };
  238. // This actually adds the .contextMenu() function to the jQuery namespace
  239. $J.fn.contextMenu = function(menu,options) {
  240. var cmenu = $J.contextMenu.create(menu,options);
  241. return this.each(function(){
  242. $J(this).bind('contextmenu',function(e){cmenu.show(this,e);return false;});
  243. });
  244. };
  245. })(jQuery);