Web Development with jQuery®

(Elliott) #1

(^262) ❘ CHAPTER 9 PLUGINS
click occurs while the mouse cursor isn’t on top of the context menu, the context menu will
be hidden.
Next, the contextmenu event is applied, and this happens by traveling up the DOM tree from our


element to the fi rst element that has the class name contextMenuContainer.
this.parents('.contextMenuContainer:first')
.bind(
'contextmenu.contextMenu',
function(event)
{
The preceding code binds the contextmenu event namespaced using our plugin’s name, contextMenu,
to the element with the contextMenuContainer class name. The function provided, of course, exe-
cutes when the contextmenu event fi res. In the fi rst line of that function, the default action, display-
ing the default system context menu is canceled. The dimensions of the viewport are retrieved from
our previously defi ned function. The contextMenu is set to display with a call to show(); then the four
CSS position properties top, right, bottom, and left are all reset to their default value, auto. This is
important because your code will set two of the four in pairs, but never all four.
event.preventDefault();
var viewport = getViewportDimensions();
contextMenu.show();
contextMenu.css({
top : 'auto',
right : 'auto',
bottom : 'auto',
left : 'auto'
});
The remaining of the contextmenu event callback function defi nes the position of the context menu
relative to the viewport based on where the user clicked inside that viewport.
if (contextMenu.outerHeight() >
(viewport.y - event.pageY))
{
contextMenu.css(
'bottom',
(viewport.y - event.pageY) + 'px'
);
}
else
{
contextMenu.css(
'top',
event.pageY + 'px'
);
}
if (contextMenu.outerWidth() >
(viewport.x - event.pageX))
[http://www.it-ebooks.info](http://www.it-ebooks.info)
Free download pdf