I've written some Javascript code with jQuery to display a dialog box on a web page that "floats" in the corder of the page.
(1) It has the following features: the dialog follows as the user scrolls the page.
(2) If the user holds down the [Ctrl] key, the dialog is hidden so that it doesn't obscure content.
I know that I tend to intuitively treat Javascript as if it were C code because it looks like C code and this is a habit I've been working to break.
Also, I'm working to write this code to be reusable and not litter the global namespace with various objects and functions.
I refer to the dialog as the "Little Black Book".
Bearing that in mind, please critique my code:
function getNewLittleBlackBook(blackBookId, blackBookWidth, blackBookHeight) {
var jQueryBlackBook = $('#' + blackBookId);
if (jQueryBlackBook.length == 0)
throw "Could not locate the element specified by blackBookId";
if (!blackBookWidth > 0 || !blackBookHeight > 0)
throw "Invalid width or height specified for Little Black Book";
var LittleBlackBook = {
id: blackBookId,
width: blackBookWidth,
height: blackBookHeight,
jQueryObj: jQueryBlackBook,
// Functions to show and hide the little black book
hide: function () { jQueryBlackBook.hide(); },
show: function () { jQueryBlackBook.show(); },
// This setPosition function determines the position based on the document scrolling.
setPosition: function () {
var windowHeight = $(self).height();
var windowWidth = $(self).width();
var scrollPosition = $(self).scrollTop();
var newModalTop = windowHeight - this.height + scrollPosition - 40;
var newModalLeft = windowWidth - this.width - 40;
this.jQueryObj.css('top', newModalTop + 'px');
this.jQueryObj.css('left', newModalLeft + 'px');
this.jQueryObj.css('height', this.height);
this.jQueryObj.css('width', this.width);
}, // end setPosition
handlers: {
ExternalScroll: function () {
LittleBlackBook.setPosition();
},
// These next two handlers serve to show/hide the Little Black Book when the user holds down the [Ctrl] key.
ExternalKeyDown: function (e) {
if (e.keyCode == 17)
LittleBlackBook.hide();
},
ExternalKeyUp: function (e) {
if (e.keyCode == 17)
LittleBlackBook.show();
}
} // end handlers
}; // end LittleBlackBook object
// Attach event handlers.
$(self).scroll(LittleBlackBook.handlers.ExternalScroll);
$(document).keydown(LittleBlackBook.handlers.ExternalKeyDown);
$(document).keyup(LittleBlackBook.handlers.ExternalKeyUp);
LittleBlackBook.setPosition();
LittleBlackBook.show();
// Return the object
return LittleBlackBook;
}