Obtaining Outer Dimensions (^) ❘ 173
Before you actually position the context menu, you need to reset your context menu’s offset posi-
tions to the defaults. All four offsets have to be reset because the next portion of code will set at
least two of the offset properties to the correct values, and the two that are set can vary depending
on where the user accesses the context menu. You don’t, for example, want the positions you set the
last time the user accessed the context menu to persist to this time because that may create a con-
fl ict. To reset each offset position, you use jQuery’s css() method to set the top, right, bottom, and
left offset properties back to each property’s default value, auto.
// Reset offset values to their defaults
contextMenu.css({
top : 'auto',
right : 'auto',
bottom : 'auto',
left : 'auto'
});
Now you’re ready to mathematically determine the proper position for the context menu. To get the
right position, you want to know if the outerHeight() of the
exceeds the browser’s viewport height (specifi ed in the vpy variable) minus the vertical point of the
mouse cursor’s position (provided in event.pageY), relative to the document. If the outerHeight()
is bigger than this calculation, it means that the menu should be positioned from the bottom, rather
than from the top; otherwise, the menu would be clipped.
// If the height or width of the context menu is greater than
// the amount of pixels from the point of click to the right
// or bottom edge of the viewport adjust the offset accordingly
if (contextMenu.outerHeight() > (vpy - event.pageY))
{
contextMenu.css('bottom', (vpy - event.pageY) + 'px');
}
else
{
contextMenu.css('top', event.pageY + 'px');
}
The same calculation is done for the horizontal portion. If the outerWidth() of the menu is greater
than the width of the viewport (specifi ed in the vpx variable) minus the horizontal coordinate of the
mouse cursor’s position (provided in event.pageX), relative to the document, the menu should be
positioned from the right, rather than the left; otherwise, the menu would be clipped horizontally.
if (contextMenu.outerWidth() > (vpx - event.pageX))
{
contextMenu.css('right', (vpx - event.pageX) + 'px');
}
else
{
contextMenu.css('left', event.pageX + 'px');
}
http://www.it-ebooks.info