DP_PanelManager

The DP_PanelManager library provides a simple, consistent way to manipulate HTML elements with features such as:

  • Visibility and Display: Hide or show HTML elements with ease.
  • Size and Position: Get the current size and position of elements and change them either directly or relatively with optional animation. Complex animations can be created by chaining animations with delays.
  • Opacity: Get and set Opacity consistently across supported browsers to create attractive “fade” effects.
  • Event management: Add and remove events programmatically to allow for better separation between logic and presentation and better management of dynamic interfaces.
  • Simple collision management (methods to tell when two panels are intersecting).
  • Can provide lists of member panels ordered by panel properties (height, width, top, left, opacity, etc). This is very useful for dynamic sorting and display of interface elements.

DP_PanelManager also provides access to useful environmental information such as mouse pointer location and window/canvas size. It makes the creation of common dynamic features like animated menus, pop-up tool tips, message boxes, etc much simpler. The library as been tested in Internet Explorer versions 6+, FireFox 1.5+ and Opera 9+.

  • The library has a very small footprint; no global variables are created.
  • Multiple instances of panel manager can be instantiated allowing for more control over related elements.
  • Highly compatible. The library normalizes access to properties and manipulations across all major browsers.

Event Abstraction code (the addEvent(), removeEvent(), and handleEvent() methods) is based in large part on code authored by Dean Edwards (2005, Original Blog Post, input from Tino Zijdel, Matthias Miller, Diego Perini).

This component requires a JavaScript (ECMAScript) 1.3 (or better) environment and has been tested successfully on Internet Explorer 6+, Firefox 1+ and Opera 9+.

Download

The component is available from GitHub:

All downloads and code are covered by our Source Code Policy.

Usage

The library consists of a single JavaScript file with a .JS extension.

Importing the Library

The library must be imported before it is used. To import the library use the <script> tag. For example:

<script type="text/javascript" src="DP_PanelManager.js"></script>

Your path may vary depending on the location of the script on your server.

Creating and Accessing the Object

Once the library has been imported you may create DP_PanelManager objects as you would any other JavaScript object. For example:

var MyPanels = new DP_PanelManager(...);

See the Constructor section for more information.

Once you have created an instance of the object you can use the methods and properties provided. See the Examples section for some sample code.

Some Terminology

There are some conceptual terms that will make understanding and using this object easier.

  • Panel Manager: Panel Managers act as a container for panels. Panel managers provide several generally useful methods and manage relative Z-Index of the member panels. Multiple panel managers (each, of course, with multiple panels) can exist on a single page.
  • Panel: An HTML element which has been imported into a Panel Manager with the PanelManager.addPanel() method or created using the PanelManager.newPanel() method. A panel can be any HTML element but is most often a DIV or some other block-level element.
  • Canvas: This is the total size (height x width) of the page. The canvas includes all positioned, displayed elements of the page regardless of window size (in other words the canvas may be larger than the displayed portion of the page).

Panel Concepts

Once a panel is imported or created the DP_PanelManager library adds methods to access and manipulate many properties of that panel. These properties are:

  • Visibility: Determines whether the element is visible (as the CSS property of the same name). Related methods are getVisibility() and setVisibility().
  • Display: Determines the display style of the element (as the CSS property of the same name). Related methods are getDisplay() and setDisplay().
  • Size: The size of the element (height and width) in pixels. Related methods are getSize(), setSize() and shiftSize().
  • Position: The position (the top-left corner) of the element relative to the top left corner of the canvas in pixels. Related methods are getPosition(), setPosition() and shiftPosition().
  • Opacity: The opacity (translucence) of the element represented as a value from 0 (transparent) to 100 (opaque). Related methods are getOpacity(), setOpacity() and shiftOpacity().
  • Order: The stack-order (z-index) of the element. Related methods are getOrder() and setOrder().

The methods provided can be generically described as follows:

  • Get Methods: Returns the current value of the property (often as an array of values). The value returned by a get method can always be used directly as input to the related set methods. For example to have one panel match the position of another panel you could do this: Panel1.setPosition(Panel2.getPosition());
  • Set Methods: Directly sets the property to the specified value. Assume the Opacity of “Panel1” was “100”. If the statement Panel1.setOpacity(50) was run the new Opacity of Panel 1 would be “50”.
  • Shift Methods: This sets the property relative to the current value. The specified values are offsets. Assume the Opacity of “Panel1” was “100”. If the statement Panel1.shiftOpacity(-20) was run the new Opacity of Panel 1 would be “80”.

In addition any manipulation can be delayed for a specified number of milliseconds. This allows complex chains of manipulations to be created.

Some manipulations (position, size and opacity) can be animated (the requested change will occur over a specified time) by including a duration. The actual number of steps (frames) in the animation is determined by dividing the duration by the interval (in milliseconds, the default value is 5). Durations must be larger than the interval to see an animation.

Panel Events

Panels also feature several methods related to event management: addEvent(), removeEvent() and handleEvent(). These methods normalize registration of events across supported browsers. These programmatically controlled events better separate programming logic from presentation code.

Panels can support many different types of events but IE developers should note that Panels use the W3C style names for events (for example “click” rather than “onclick”). Supported events will differ across platforms but some common ones are: click, mousedown, mouseup, mouseover, focus, submit, change, blur, keyup, keydown, etc.

Panel events call a handler (a JavaScript function) and pass that function the current event object (which may differ between browsers although PanelManager normalizes some aspects). The handler is called as a method of the Panel (the HTML element) which means the “this” keyword in the handler will reference the Panel on which the event fired.

Timing Considerations

Millisecond times entered for delays and animation durations should be considered approximations. Browsers will generally be close but may lag (or speed up) for various technical reasons. Also animation time will be slightly altered between browser brands and versions – what looks great in IE might run (slightly) too fast or too slow in FireFox or Opera and vice versa.

Animations are performed asynchronously (frames are defined in advance when the call is encountered then started). In other words code following an animation request will begin immediately – it will not “wait” for the animation to be completed. You must consider this when creating complex animations and use the delay parameter appropriately.

For example the following code will not work as you might expect:

	myPanel.setOpacity(0, 0, 500);
	myPanel.setDisplay("Hide");
	

The first line requests that the element “fade out” over 500 milliseconds. However the second line runs immediately after the first but before the animation has started. It hides the element before the animation can be seen. To perform the desired action use the “delay” argument like this:

	myPanel.setOpacity(0, 0, 500);
	myPanel.setDisplay("Hide", 500);
	

Now the second line, although it will still be run immediately after the first, will delay its action for 500 milliseconds.

Animation Considerations

Animations of different properties can be overlapped (for example moving something as you make it larger or sliding something to the left as it fades out). Overlapping animations of the same property (for example multiple setPosition() animations) will conflict with one another and create a frenetic, unattractive animation.

Large numbers of simultaneous animations can easily overwork even powerful systems. Also note that some manipulations (especially changing size or display) may force the browser to dynamically reflow it’s display. This may interfere with animation by causing stuttering or other visual inconsistencies.

Constructor

DP_PanelManager()

The constructor. Used to create DP_PanelManager instances.

Method Signature

new DP_PanelManager([AnimationInterval], [ZFront], [ZBack], [ZBase])

Arguments

  • AnimationInterval: Number (of milliseconds), Optional. Defaults to “5”. The interval to use for animations (the number of frames in an animation is a result of duration divided by interval). Lower intervals will produce more frames (smoother animation) while higher intervals will produce fewer frames (rougher animation). A higher animation interval (fewer frames) will consume fewer system resources than a lower one.
  • ZFront: Number, Optional. Defaults to 500. The value to apply when an element’s order is set with setOrder(“tofront”).
  • ZBack: Number, Optional. Defaults to -500 (negative 500). The value to apply when an element’s order is set with setOrder(“toback”).
  • ZBase: Number, Optional. Defaults to 0 (zero). The value to apply when an element’s order is set with setOrder(“tobase”).

Return

A reference to the new DP_PanelManager.

Properties and Methods

There are several properties available in a DP_PanelManager instance. It’s rare to modify these properties directly:

  • Panels: An object containing a reference to all member panels where the property name (key) is the same as the HTML ID. A reference to any member panel can be obtained with “PanelManager.Panels[ID]” (this is functionally equivalent to “document.getElementById(ID)”). Member panels can also be accessed via a for..in loop over the Panels property.
  • AnimationInterval: The interval (in milliseconds) to use for animations (the number of frames in an animation is a result of duration divided by interval).
  • ZFront: The value to apply when an element’s order is set with setOrder(“tofront”).
  • ZBack: The value to apply when an element’s order is set with setOrder(“toback”).
  • ZBase: The value to apply when an element’s order is set with setOrder(“tobase”).

DP_RequestPool methods available:

Note that in method/function signatures a pipe (“|”) indicates “OR” while arguments in square brackets are optional.

getWindowSize()

Returns the current Window (browser) size.

Method Signature

getWindowSize(Request)

Arguments

This method has no arguments:

Return

An array of values in the form of [Height, Width].

getCanvasSize()

Returns the current canvas (page) size.

Method Signature

getCanvasSize()

Arguments

This method has no arguments:

Return

An array of values in the form of [Height, Width].

getMousePosition()

Returns the current mouse position for the specified event. See the Examples section for more information.

Method Signature

getMousePosition(Event)

Arguments

This method has one argument:

  • Event: Event Object, required. A DOM Event object.

Return

An array of the mouse coordinates (relative to the canvas) in the form of [Top, Left].

newPanel()

Creates a new HTML element, appends it to the document BODY and adds it to the panel manager. The element will be created with a position of “absolute” and a display of “none” (in other words the new element will be automatically hidden until you position it and display it).

Method Signature

newPanel(PanelId, PanelElement, DefaultDisplay)

Arguments

This method has three arguments:

  • PanelId: String (a valid HTML ID), Optional. Defaults to null. The HTML ID of the new element (should not conflict with existing IDs).
  • PanelElement: String, optional. Defaults to “div”. The type of element to create (a valid HTML element). Usually a block-level element (div, p, h1, etc) but can be any valid element. Remember however that the element will be appended to the BODY; care should be taken to preserve valid HTML structure.
  • DefaultDisplay: String, optional. Defaults to “block”. This is the default display style to apply to the element when the display is set with setDisplay(“show”).

Return

A reference to the newly created panel.

getPanelList()

Sorts all panels in the manager panels by the specified property and returns an array of panel references in that order.

Method Signature

getPanelList(Property)

Arguments

This method has one argument:

  • Property: String (a valid panel property), Optional. Defaults to nothing (an array of all panels in no particular order will be returned). The property used to order the panels. Valid property values are:
    • height: The height of the panels.
    • width: The width of the panels.
    • top: The top position of the panels (vertical position on the page, from top to bottom).
    • left: The left position of the panels (horizontal position on the page, from left to right).
    • opacity: The Opacity of the panels.
    • order: The order of the panels (z-index value, from back to front).
    • id: ID of the panel, sorted alphabetically.

Return

Array of references. All panels in the manager ordered by the specified property.

addPanel()

Adds an existing HTML element to the Panel Manager.

Method Signature

addPanel(Element, [DefaultDisplay])

Arguments

This method has two arguments:

  • Element: Object Reference to an element (as from “getElementsByTagName()”) or a String (a valid HTML ID), required. The HTML element to add (either by direct object reference or by HTML ID).
  • DefaultDisplay: String, optional. Defaults to current value of the elements style.display value. This is the default display style to apply to the element when the display is set with setDisplay(“show”). This argument is rarely used (being more for internal use).

Return

A reference to the newly added panel.

Panel Properties and Methods

Once a panel is added to a Panel Manager several properties and methods are added to the panel.

Panel properties available:

  • panelManager: A reference to the PanelManager instance that holds this panel.
  • DefaultDisplay: The default display property (used for the setDisplay(“show”) method).

DP_RequestPool methods available:

Note that in method/function signatures a pipe (“|”) indicates “OR” while arguments in square brackets are optional.

PanelInstance.load()

Loads new content into a panel. The content added is scanned for script tags, if any are found the script is added to the document (script dynamically included in a document is not normally parsed as script).

Note that there is a bug in Internet Explorer 6 in this regard: script, style and link tags must appear AFTER displayable content for them to be honored in loaded content. If you place any of these tags first in the content IE (but not FireFox or Opera) will ignore them.

Method Signature

load(Content)

Arguments

This method has one argument:

  • Content: String, required. The new content with which to populate the panel.

Return

None.

PanelInstance.getVisibility()

Returns the current value of the visibility property.

Method Signature

getVisibility()

Arguments

This method has no arguments:

Return

String. The current value of the visibility property (usually “visible”, “hidden” or an empty string).

PanelInstance.setVisibility()

Sets the visibility property.

Method Signature

setVisibility(Action, [Delay])

Arguments

This method has two arguments:

  • Action: String, required. Can be one of the following:
    • show: A convenience value which will set the value of the property to “visible”.
    • hide: A convenience value which will set the value of the property to “hidden”.
    • toggle: A convenience value which will set the value of the property to “visible” if the current value is “hidden” and set the value to “hidden” if the current value is “visible”.
    • Some Other Value: If any other value is passed the property will be set to that value.
  • Delay: Number, Optional. The number of milliseconds to delay the change.

Return

None.

PanelInstance.getDisplay()

Returns the current value of the display property.

Method Signature

getDisplay()

Arguments

This method has no arguments:

Return

String. The current value of the display property (common values are “block”, “inline”, “none” or an empty string).

PanelInstance.setDisplay()

Sets the display property.

Method Signature

setDisplay(Action, [Delay])

Arguments

This method has two arguments:

  • Action: String, required. Can be one of the following:
    • show: A convenience value which will set the value of the property to current value of the “DefaultDisplay” property (this defaults to “block”).
    • hide: A convenience value which will set the value of the property to “none”.
    • toggle: A convenience value which will set the value of the property to the value of the “DefaultDisplay” property if the current value is “none” and set the value to “none” if the current value is anything else.
    • Some Other Value: If any other value is passed the property will be set to that value.
  • Delay: Number, Optional. The number of milliseconds to delay the change.

Return

None.

PanelInstance.getOrder()

Returns the current order of the element (the value of the style.z-index property).

Method Signature

getOrder()

Arguments

This method has no arguments:

Return

Number. Positive or negative number or zero.

PanelInstance.setOrder()

Sets the order property (the style.z-index property).

Method Signature

setOrder(Action, [Delay])

Arguments

This method has two arguments:

  • Action: String or Number, required. Can be one of the following:
    • tofront: Sets the order to the Panel Manager value of ZFront (defaults to 500).
    • toback: Sets the order to the Panel Manager value of ZBack (defaults to -500).
    • tobase: Sets the order to the Panel Manager value of ZBase (defaults to 0).
    • Some Number: Sets the order to the specified value.
  • Delay: Number, Optional. The number of milliseconds to delay the change.

Return

None.

PanelInstance.hasCollisionWith()

Determines whether the two panels are overlapping (colliding).

Method Signature

hasCollisionWith(Element)

Arguments

This method has one argument:

  • Element: Object Reference to a Panel element (as from “getElementsByTagName()”) or a String (a valid HTML ID of a Panel), required. The Panel to test (either by direct object reference or by HTML ID).

Return

Boolean. “True” if the panels collide, “False” if not.

PanelInstance.getDistanceFrom()

Returns the distance (in pixels) between one panel and another and the direction of those panels. Note that distance is determined from the outside edges of the panels such that panels with a distance of zero will be touching (but not overlapping) each other while direction is determined from the center of the panels.

“Distance” is related in pixels in the X and Y axis. The following general inferences can be made from the “Distance” results:

  • [postive value, positive value] = The elements do not overlap on either axis. The elements are diagonal to each other.
  • [postive value, negative value] = The elements overlap vertically but do not touch.
  • [negative value, positive value] = The elements overlap horizontally but do not touch.
  • [negative value, negative value] = The elements overlap.

Zero values indicate that the panels are “touching” (but not overlapping) on that axis. Touching any of the four opposite corners of two panels will return a “[0,0]” result.

“Bearing” describes the direction that the target panel lies in. The value returned is a number from 0 to 359.99 such that:

  • 0 indicates that the target is directly above (“North”) of the panel.
  • 90 indicates that the target is directly right (“East”) of the panel.
  • 180 indicates that the target is directly bel0w (“South”) of the panel.
  • 270 indicates that the target is directly left (“West”) of the panel.

Bearing is determined from the center of the panels.

“Direction” is a rougher indication of Y and X direction useful for gross tests. The values returned are:

  • 1: The target is above (for the X) or to the right (for the Y).
  • 0: The target is directly in-line with the axis.
  • -1: The target is below (for the X) or to the left (for the Y).

Directionality is determined from the center of the panels.

Method Signature

getDistanceFrom(Element)

Arguments

This method has one argument:

  • Element: Object Reference to a Panel element (as from “getElementsByTagName()”) or a String (a valid HTML ID of a Panel), required. The Panel to test (either by direct object reference or by HTML ID).

Return

Array. In the form of [Y-Distance, X-Distance, Bearing, Y-Direction, X-Direction].

PanelInstance.getPosition()

Returns the pixel coordinates of the element from the top-left corner of the canvas.

Method Signature

getPosition()

Arguments

This method has no arguments:

Return

Array. In the form of [Top, Left].

PanelInstance.setPosition()

Sets the position of the element.

Method Signature

setPosition(TopLeft, [Delay], [Duration])

Arguments

This method has three arguments:

  • TopLeft: Array of Integers ([Top, Left]), Required. The new coordinates of the element. Setting either coordinate to null will leave that value unchanged.
  • Delay: Number, Optional. The number of milliseconds to delay the change.
  • Duration: Number, Optional. The length of time, in milliseconds, to complete the animation.

Return

None.

PanelInstance.shiftPosition()

Alters the position of the element relative to the current position of the element.

Method Signature

shiftPosition(TopLeft, [Delay], [Duration])

Arguments

This method has three arguments:

  • TopLeft: Array of Integers ([Top, Left]), Required. The amounts to alter the current values by. Setting either value to null will leave that value unchanged.
  • Delay: Number, Optional. The number of milliseconds to delay the change.
  • Duration: Number, Optional. The length of time, in milliseconds, to complete the animation.

Return

None.

PanelInstance.getSize()

Returns the pixel size of the element.

Method Signature

getSize()

Arguments

This method has no arguments:

Return

Array. In the form of [Height, Width].

PanelInstance.setSize()

Sets the size of element.

Method Signature

setSize(HeightWidth, [Delay], [Duration])

Arguments

This method has three arguments:

  • TopLeft: Array of Integers ([Height, Width]), Required. The new size of the element. Setting either value to null will leave that value unchanged.
  • Delay: Number, Optional. The number of milliseconds to delay the change.
  • Duration: Number, Optional. The length of time, in milliseconds, to complete the animation.

Return

None.

PanelInstance.shiftSize()

Alters the size of the element relative to the current size of the element.

Method Signature

shiftSize(HeightWidth, [Delay], [Duration])

Arguments

This method has three arguments:

  • TopLeft: Array of Integers ([Height, Width]), Required. The amounts by which to change the size of the element. Setting either value to null will leave that value unchanged.
  • Delay: Number, Optional. The number of milliseconds to delay the change.
  • Duration: Number, Optional. The length of time, in milliseconds, to complete the animation.

Return

None.

PanelInstance.getOpacity()

Returns the current Opacity of the element normalized as a value between 0 (transparent) and 100 (opaque).

Method Signature

getOpacity(Opacity)

Arguments

This method has no arguments:

Return

Number. The current opacity represented by a value from 0-100.

PanelInstance.setOpacity()

Sets the Opacity of the panel.

Method Signature

setOpacity(Opacity, [Delay], [Duration])

Arguments

This method has three arguments:

  • Opacity: Number (a value from 0 to 100), Required. The new opacity of the element.
  • Delay: Number, Optional. The number of milliseconds to delay the change.
  • Duration: Number, Optional. The length of time, in milliseconds, to complete the animation.

Return

None.

PanelInstance.shiftOpacity()

Alters the opacity of the element relative to the current opacity of the element.

Method Signature

shiftOpacity(Opacity, [Delay], [Duration])

Arguments

This method has three arguments:

  • Opacity: Number (a value from -100 to 100), Required. The amount by which to change the opacity of the element.
  • Delay: Number, Optional. The number of milliseconds to delay the change.
  • Duration: Number, Optional. The length of time, in milliseconds, to complete the animation.

Return

None.

PanelInstance.addEvent()

Registers a handler (a JavaScript function) with an Event (such as “click” or “mousedown”).

Method Signature

addEvent(Type, Handler)

Arguments

This method has two arguments:

  • Type: String, Required. The type of event for which the handler will be registered (for example “click” or “onload”).
  • Handler: Function. The function to call when the event fires. This function will be called as a method of the current panel (meaning that the “this” keyword will reference the panel) and be passed the DOM Event object which represents the event.

Return

None.

PanelInstance.removeEvent()

Removes the specified event handler from the Panel.

Method Signature

removeEvent(Type, Handler)

Arguments

This method has two arguments:

  • Type: String, Required. The type of event for which the handler is registered (for example “click” or “onload”).
  • Handler: Function. The function registered as a handler.

Return

None.

PanelInstance.handleEvent()

This abstracted event handler will launch all handlers associated with the event type of the passed event object. This method is generally only used internally but may, in some rare cases, be usable directly.

Method Signature

handleEvent(Event)

Arguments

This method has one argument:

  • Event: Event Object, required. A DOM Event object.

Return

Boolean. Will return “false” if any of the registered event handlers return false. Returns “true” otherwise.

Examples

Panel Mananger Demo

The Panel Manager Demo allows you to create and manipulate panels using the various panel methods. See the end of this section for more practical examples of use.

Instantiating a PanelManager

You instantiate a PanelManager for use as you would any other JavaScript Object. The following line will instantiate a PanelManager calls “MyPanels”:

MyPanels = new DP_PanelManager();

At this point the PanelManager is created and ready to be used. You can now use the general methods getWindowSize(), getCanvasSize(), getMousePosition(), newPanel() and addPanel(). However the PanelManager does not, at this point, actually contain any panels.

You can create as many PanelManagers as required. For example you might want to create a PanelManager to contain all panels related to a menu and another to hold all the panels related to the content area. This would allow you to easily access these collections as single units (for example you could easily hide all menu items by looping over the Panels property of the appropriate PanelManager).

Creating Panels

Panels can be created using either the newPanel() or addPanel() methods.

Using newPanel() creates a new HTML element and adds it to the document (appending it to the BODY element). The ID of the panel becomes the HTML ID of the new element. For example:

myPanel1 = PanelManager.newPanel("myPanel1");

The above creates a new DIV element (the default element type) as the last child of the BODY element. The new element’s HTML ID is “myPanel1”. Panels created in this way are, by default, hidden from view. Use the setDisplay() method to reveal them.

Using addPanel() allows you create a panel from an existing HTML element (referenced by the HTML ID). Assuming that there’s a DIV on the page with an ID of “MenuItem1” you could create a panel out of this element using:

myPanel2 = PanelManager.addPanel("MenuItem1");

Once a panel is created it is accessible, using indexed notation by ID, in the “Panels” property (a JavaScript object) of the PanelManager. All Panel-specific methods will be available directly as methods of the element: any method (getElementById, getElementByTagName, etc) that returns a reference to the element can be used to access all panel-specific methods. Considering the above example the following would both work:

PanelManager.panels["MenuItem1"].getPosition();
document.getElementById("MenuItem1").getPosition();

Manipulating Panels

Once you have a reference to the panel (the HTML element) you can call panel methods to easily manipulate panels. You can also, of course, still access all general HTML properties and styles. For example to assuming the PanelManager “MyPanels” you could create a new panel, set it’s size, color and content and then cause it to fade slowly into view using the following code:

		// Create the Panel
	CurPanel = MyPanels.newPanel("myPanel1");
			// Size and position
	CurPanel.setSize([200, 200]);
		// Style the Panel
	CurPanel.style.backgroundColor = "#cccccc";
		// Load Content
	CurPanel.load("<div style='padding: 10px'>This is Panel One!</div>");
		// Set the Panel Opacity to 0 (completely transparent)
	CurPanel.setOpacity(0);
		// Display the (now transparent and thus invisible) panel
	CurPanel.setDisplay("show");
		// Fade the panel in over five seconds
	CurPanel.setOpacity(100, 0, 5000);
	

Although most lines in the above code simply run and take immediate effect the last line uses the “duration” argument to define an animation. The panel will take 5 seconds (5000 milliseconds) to fade from opacity 0 (completely transparent) to opacity 100 (completely opaque).

Remember that all “set” and “shift” manipulations will be launched as soon as they’re encountered in the code. To chain manipulations into complex effects use the “delay” argument in these methods to postpone effects. Let’s assume that after your panel is fully visible you want to, over one second, slide it 200 pixels to the right. You can do this by added the following (note that the relative “shift” method is used rather than the direct “set” method):

		// Slide the panel to the left
	CurPanel.shiftPosition([null,200], 5000, 1000);
	

The second argument (“5000”) is the number of milliseconds to delay the change – in this case 5 seconds (or, to be more specific, right after the fade animation is complete). The third argument is the duration, again in milliseconds, for the this animation (in this case the panel will take 1 second to move 200 pixels to the right).

Manipulations can also cross over. Finally assume that halfway through the movement you want your panel to start growing wider. You could add this line:

		// Widen the panel
	CurPanel.shiftSize([0,100], 5500, 500);
	

This animation increases the size of the panel by 50% (100 pixels) but waits for 5.5 seconds to do it (so it will begin about halfway through the movement animation). Once it starts it runs concurrently with the shiftPosition() method.

The manipulations you can perform are essentially endless.

Managing Panel Events

Cross-browser event management can present challenges. The abstraction methods provided to Panels can help to simplify this. Events are any of a collection of actions that can be recognized by the browser: clicking the mouse, pressing a keyboard key, resizing a window. Handlers are functions which run after a specified event has occurred (such as highlighting a tab when it’s been clicked). Linking handlers to events is the core function of event management.

To link a handler to an event use the addEvent() method. Pass it an event (such as “click”) and a function to run when that event occurs. You can add multiple handlers to a single event, but duplicate handlers will be discarded. For example to run the “doStuff()” function when a panel is clicked use this:

MyPanel.addEvent("click", doStuff);

Note that the doStuff function is passed as data (in other words the function itself is passed, “doStuff”, not a call to the function as in “doStuff()”). You can place arbitrary code in a handler, but it must be wrapped in a function. To add an alert to the panel you could do this:

MyPanel.addEvent("click", function() {alert("Hello")});

To remove events from panels use the removeEvent() method and pass it the exact same parameters used to create the event. To remove the events we just added us this:

MyPanel.removeEvent("click", doStuff);
MyPanel.removeEvent("click", function() {alert("Hello")});

Handler functions are called as methods of the Panel to which they’ve been assigned and will be passed a DOM “event” object representing the current event. This means that within the handler the “this” keyword will refer to the panel. This greatly simplifies the creation of handlers. Assume that we have three Panels, One, Two and Three and that we want the current position of a panel to be displayed when it’s clicked. The following code would accomplish this:

		// Create the Handler
	showSize = function(event){
		alert(this.getSize());
	};
	One.addEvent("click", showSize);
	Two.addEvent("click", showSize);
	Three.addEvent("click", showSize);
	

Although there is only one handler it’s called in the context of the clicked panel making it applicable to all of them.

Managing events in this manner can greatly streamline and simplify your code.

Working with Mouse Position

Getting the mouse position requires an event object. Event objects describe the environment and circumstances of an event (mouse and keyboard states, the element and action related to the event and so forth). Event objects are automatically created (in modern browsers) whenever an event is fired and passed to any registered event handlers.

Here is a simple event handler for the “mousemove” event. This handler then passes the event object to the DP_PanelManager getMousePosition() method:

	document.onmousemove = function(Event) {
		CurMouseCoords = PanelManager.getMousePosition(Event);
		...
	};
	

All events create an Event object that can be to getMousePosition() method. A common requirement is to track not only that an object was clicked, but where it was clicked. We can do this easily using DP_PanelManager by creating the following event handler:

	getClickPos = function(Event) {
			// Get the Current Mouse Position
		var CurMousePos = PanelManager.getMousePosition(Event);
			// Get the Current Panel Position
		var CurPanelPos = this.getPosition();
			// Calculate the Panel Click Position
		var CurTop = CurMousePos[0] - CurPanelPos[0];
		var CurLeft = CurMousePos[1] - CurPanelPos[1];
			// Show the results
		alert([CurTop,CurLeft]);
	};
	myPanel.addEvent("click", getClickPos);
	

The last line registers the handler to the “click” event of “myPanel”. Now, when clicked, the getClickPos() handler will run. The related Event object will be automatically created and passed to it.

The handler passes the event object forward to getMousePosition() which returns the mouse position relative to the canvas. The handler then (using the “this” keyword) gets the position of the clicked panel, again realtive to the canvas.

Because all positions returned are in the form of “[Top,Left]” the calculation to get the click location on the panel is simple: current mouse position minus the panel position.

The event handler then alerts the user to the click location.

More About Events

A full discussion of events and how to work with the Event object is beyond the scope of these instructions. Information on the Internet Explorer implementation of events can be found at the Microsoft Developer’s Network while information related to FireFox and other Mozilla browsers can be found at the Mozilla Developer Center.

Practical Examples

The following examples provide insight into “real-world” usages of the component and explore how it can be used to meet common development tasks.

Animated Menu

A fairly simple animated menu. When the mouse is over each menu item a panel appears with content. This code demonstrates many aspects of DP_PanelManager:

  • The “menu” panels are generated from pre-existing (and relatively positioned) HTML Elements. Moving the menu (for example by changing the padding of the containing elements) will not affect the functionality.
  • The “popup” panels are created on the fly and then positioned relative to their parent menu items. Note that the popups are actually created as properties of the menu items. This makes accessing them later much simpler.
  • The mouseover and mouseout events are managed using the DP_PanelManager abstractions. Notice how the event handler functions make use of the “this” keyword and use the “delay” attribute to chain the animations.

Drag-and-Drop with Collision Detection

Next is a simple drag-and-drop demonstration which also demonstrates collision detection. Although the library does not, directly, support drag and drop functionality it does simplify building such functionality. Using collision detection allows you to perform actions when panels “collide” (overlap). In this example the dragged panel will change color when colliding with another panel.

Drag-and-Drop with Ordering

Next is a more complex drag-and-drop demonstration which also demonstrates ordering of elements built using the getPanelList() method. Again while the library does not provide this functionality directly it greatly eases the complexity of implementation.

Note that two panel managers are used in this example: one to hold the orderable elements and another used for just the BODY element. This prevents the BODY element from being returned in the Ordered PanelList.

It’s a Frog. (Drag and Drop, Collision, Bearing and a Fly.)

This is just a toy that demonstrates drag-and-drop with bearing resolution (the Frog’s eyes will follow the fly) and collision detection.

Popup Definitions

Now we have a common problem: showing definitions for words or concepts without leaving the content. This example provides popup definitions for highlit words when you mouse over them.

Useless Animation

This last example is essentially useless. It creates a grid of many panels and then randomly alters their properties. It is fun to watch (at least for a little while) and does demonstrate several aspects of DP_PanelManager.

Revision History

June 8, 2013

  • Initial GITHUB release.

April 23, 2008

  • Updated “getDistanceFrom()” to include bearing (direction on a 360 degree plane) and directionality (on the Y/X axis).
  • Added a new example to demonstrate this new feature.

November 21, 2007

  • Fixed bug with “setOrder()” panel method when passing a numeric value.
  • Added new panelManager method “getPanelList()”. This method accepts a property (Height, Width, Top, Left, Opacity, Order, ID) and returns an array of references to the Panels in the mananger ordered by that property.

November 20, 2007

  • Added new panel method “hasCollisionWith()”. This method accepts a panel as input and returns “false” if the panels are not overlapping (colliding) and “true” if they are.
  • Added new panel method “getDistanceFrom()”. This method accepts a panel as input and returns the distance (as an array in the format [Y,X]) between the panels. A negative value indicates that the panels are overlapping in that axis (such that both value being negative indicate that the panels are directly overlapping).

September 28, 2007

  • You can now create a panel out of the “window” object. This allows you to manage window events but most panel methods will will error (as the window object lacks a style element).

May 01, 2007

  • The component now allows for “anonymous” members – HTML elements without IDs.
  • New panels can now be generated anonymously (without IDs).
  • Closures, rather than evaluate, are now used for the generation of animation frames. This should speed animation slightly and eliminates some animation cross-over problems.

April 11, 2007

  • Initial Release.

1 Comment

Comments are closed.