Web Development with jQuery®

(Elliott) #1

Writing a Plugin (^) ❘ 263


{


contextMenu.css(
'right',
(viewport.x - event.pageX) + 'px'
);
}
else
{
contextMenu.css(
'left',
event.pageX + 'px'
);
}

A little bit of math and comparison determines whether it is best to place the context menu from


the left or right, and whether from the top or from the bottom is better. The size of the context


menu is taken into consideration, along with where the mouse click occurs in relation to the edges


of the viewport. The properties event.pageX and event.pageY, obviously provided with all the other


event data, are the x,y coordinates of the mouse click in relation to the document. The properties


viewport.x and viewport.y contain the width and height of the viewport. Finally, outerHeight() is


a jQuery method that gets the height of the context menu including the following CSS properties:


height, padding, border-width, and margin. Likewise, outerWidth() provides similar dimensions


for width.


Next, an event is attached to the document to track clicks that occur outside the context menu.


if (!$('body').data('contextMenu'))
{
$('body').data('contextMenu', true);

$(document).bind(
'mousedown.contextMenu',
function()
{
$('div.contextMenu').each(
function()
{
if (!$(this).data('contextMenu')
{
$(this).hide();
}
}
);
}
);
}

If the element does not have the data contextMenu, or contextMenu is set to false, then the


event is attached. So that the event cannot be attached multiple times, the contextMenu data is set


to true on the element to indicate that the event has been attached.


$('body').data('contextMenu', true);

http://www.it-ebooks.info

Free download pdf