HiveBrain v1.2.0
Get Started
← Back to all entries
patternjavascriptMinor

Simple Javascript Widget without cluttering global namespace?

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
withoutsimpleglobalnamespacejavascriptclutteringwidget

Problem

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.

Solution

You should throw Error objects rather than strings:

throw new Error("Invalid width or height specified for Little Black Book");


This provides a stack trace.

Code Snippets

throw new Error("Invalid width or height specified for Little Black Book");

Context

StackExchange Code Review Q#3103, answer score: 3

Revisions (0)

No revisions yet.