Web Development with jQuery®

(Elliott) #1

(^172) ❘ CHAPTER 6 CSS
When you create your own context menu, you want to have the position of your context menu
change depending on where in the browser window the context menu is accessed. If the user
accesses the context menu close to the left and top sides of the window, you want your context menu
to position itself from the left and the top. If the user accesses the context menu from the right and
bottom of the window, then you want the context menu to intelligently reposition from the right and
bottom and do this without any part of the context menu being obstructed.
To make the context menu so that it dynamically repositions itself depending on where it is
accessed, you need to do a little bit of math. The fi rst bits of data that you need to do that math
are the dimensions of the viewport. Use the dimensions of the viewport to help determine how the
context menu should be positioned relative to the place where the user accesses it. Getting the view-
port’s dimensions, unfortunately, is one of those fringe areas in which different browsers implement
different methods of doing the same thing, and jQuery doesn’t provide a neat, unifi ed method of
patching over this particular difference. This is less of a nuisance today because recent versions of
Internet Explorer have come more in line with the defi ned standards. The following code intelli-
gently obtains the viewport’s dimensions depending on the browser’s implementation:
// The following bit gets the dimensions of the viewport
// Thanks to quirksmode.org
var vpx, vpy;
if (self.innerHeight)
{
// all except Explorer
vpx = self.innerWidth;
vpy = self.innerHeight;
}
else if (document.documentElement &&
document.documentElement.clientHeight)
{
// Explorer 6 Strict Mode
vpx = document.documentElement.clientWidth;
vpy = document.documentElement.clientHeight;
}
else if (document.body)
{
// other Explorers
vpx = document.body.clientWidth;
vpy = document.body.clientHeight;
}
// Reset offset values to their defaults
contextMenu.css({
top : 'auto',
right : 'auto',
bottom : 'auto',
left : 'auto'
});
http://www.it-ebooks.info

Free download pdf