Web Development with jQuery®

(Elliott) #1

(^174) ❘ CHAPTER 6 CSS
That’s all there is to positioning the context menu correctly based on where the user clicks in the
document. The additional code handles revealing and hiding the context menu at the right moments.
At the beginning of the document, you declare the following variable:
var contextMenuOn = false;
The preceding variable is used to track whether the user’s mouse cursor is over the context menu
when it is active. When the user’s mouse cursor leaves the context menu, this variable is set to false;
when the user’s mouse cursor is present, this variable is set to true. This boolean value is then used
to toggle the menu off when the user clicks an area outside the context menu and keeps the menu
active when the user clicks the menu itself.
The following code handles the part that sets the contextMenuOn variable to either true or false via
passing two event handlers to jQuery’s hover() method:
$('div#contextMenu').hover(
function()
{
contextMenuOn = true;
},
function()
{
contextMenuOn = false;
}
);
Then the following code hides the menu when the user clicks anywhere outside the menu because
the variable is false in that case and keeps the menu on when the user actually clicks the menu.
$(document).mousedown(
function()
{
if (!contextMenuOn)
{
$('div#contextMenu').hide();
}
}
);
jQuery’s API as it relates to CSS is documented in Appendix B and Appendix H.


Summary


In this chapter, you learned how to get the value of an element’s CSS property using jQuery’s css()
method. You also learned how to manipulate an element’s style using the same css() method, which
can be done by passing a property and value to the css() method as two separate strings, or by
passing an object literal with one or more property, value pairs.

jQuery provides the offsetHeight and offsetWidth properties by calling the methods outerHeight()
or outerWidth(). These methods return an element’s pixel width or height, including padding and
borders. You can also specifi cally add margin to the value returned by these methods.

http://www.it-ebooks.info

Free download pdf