Floatbox v5.0 - Programmer's API Reference

floatboxjs.com

Index

Variables and Properties

fb

Floatbox's primary object is the global variable "fb".
The API functions and variables are all accessed as properties of this fb namespace.
Each window that includes floatbox.js in its document has its own fb object defined and available.
If a child iframe does not have floatbox.js included in its document, the Floatbox API can still be accessed from the parent or top document using "parent.fb" or "top.fb".

fb.instances

Floatbox can display multiple boxes at one time, such as when displaying an info box over top of a displayed image or when showing multiple non-modal sibling boxes.
Each floatbox instance that is opened is added to the fb.instances array.
The order of the array is always the chronological order in which the boxes were opened.
The primary or first floatbox is always fb.instances[0].

Floatbox component nodes and some API functions are properties of the instances. For example: fb.instances[1].fbContent and fb.topInstance.resize( ).
For convenience and legacy code support, the component nodes such as fbContent for the first loaded floatbox are accessible as properties of the top page's "fb" object. E.g., fb.fbContent is equivalent to fb.instances[0].fbContent.

Most API functions that act on a particular instance can be called as a member function of the instance, or can be called from the "fb" namespace with an optional instance parameter. When calling from the fb namespace, if the instance parameter is not provided, the instance acted upon will be the clicked floatbox (if clicked) or fb.topInstance.

fb.lastInstance

fb.lastInstance always points to the most recently loaded floatbox instance.
If no floatboxes are open, fb.lastInstance will be null or undefined.
fb.lastInstance is always identical to fb.instances[fb.instances.length-1].
For legacy code support, the deprecated fb.lastChild is still available on the API and is equivalent to fb.lastInstance.

fb.topInstance

If you are working with modal floatboxes (the default), fb.topInstance will always be the same as fb.lastInstance.
Multiple non-modal floatboxes can have their stack order changed by user interaction or by code.
When non-modal boxes are re-stacked, fb.topInstance will always point to the box that is currently displayed on top of all others.
For legacy code support, the deprecated fb.topBox is still available on the API and is equivalent to fb.topInstance.

<instance>.fbContent

fbContent is the DOM node (element) holding the content that is displayed by a floatbox. It may be an img, iframe, or div depending on what kind of content is currently showing.
Having this node reference can be helpful when dynamically working with floatboxed iframe or div html content.
Use the 'lastInstance', 'topInstance', or the 'instances' array of pointers to get to the fbContent element for secondary (stacked) floatboxes - e.g. fb.topInstance.fbContent or fb.instances[2].fbContent.
For convenience and legacy code support, the fbContent node for the first or primary floatbox can be accessed from the top document's fb object as fb.fbContent.

fb.ieVersion

An integer indicating which version of Internet Explorer (if any) the visitor is currently using. fb.ieVersion will be 0 in non-IE browsers and will be 6 or greater in IE.
Example usage: if ( fb.ieVersion < 9 )...

fb.mobile

This will be set to true if the visitor's browser is Mobile Safari based, such as an iPhone or Android device.

Back to Index

Functions

fb.start ( source, options )

fb.start creates and invokes a floatbox.
The 'source' parameter is overloaded. It can be a URI string (path to the content), a DOM element, an element's id, or a string of HTML.
The optional 'options' parameter can accept a string of floatbox options formatted the same as for data-fb-options attributes, or can accept an associative array of option name:value pairs.
For support of legacy code, fb.start will still accept the deprecated object parameter { href: strURL, rev: strOptions, title: strTitle, html: strHTML }.

Examples:
Load an image in floatbox with some options.
fb.start( 'path/image.jpg', 'controlsPos:tr caption:`my caption`' );
or fb.start( 'path/image.jpg', { controlsPos: 'tr', caption: 'my caption' } );

Launch an existing anchor in floatbox. Pass the anchor element or its id to fb.start().
fb.start( 'someAnchorId' ); or fb.start( fb.$('someAnchorId') );

Open inline hidden div content.
fb.start( '#someDivId' ); or fb.start( fb.$('someDivId') );

Use direct html as the content source.
fb.start( '<p>hello world</p>', 'roundCorners:none showClose:false' );
(The direct content string must contain '<' and '>' to be recognized as html.)

A dynamically added anchor could launch itself in floatbox with:
<a href="image1.jpg" onclick="fb.start( this ); return false;">click me</a>
The anchor does not need a floatbox class and does not have to be activated by fb.activate().

Note that the options parameter can itself contain a 'source' option which will override the first source parameter. This allows you to define the entire start action in one associative array, and invoke a box based on that array with fb.start( null, myOptionsObject );

fb.end ( arg )

Call fb.end() to close a running floatbox.
The 'arg' parameter is optional.
With multiple boxes open, you can close a particular one by passing the instance number or the actual floatbox instance object. E.g., fb.end( 1 ) and fb.end( fb.instances[1] ) are equivalent.
If 'arg' is a boolean value of true, all boxes will be closed.
If 'arg' is a string and there is only one floatbox currently open, arg is assumed to be a URL and the base page will attempt to navigate to that URL when the floatbox end completes. The string 'self' will cause the currently loaded base page to refresh, while 'back' will load the previous item from the browser's history.

If an instance is not specified by the 'arg' parameter, the floatbox instance to be closed will be either the box containing the element that was clicked to invoke the code that calls fb.end, or fb.topInstance.
The 'end' function is also available directly on each instance. For example: fb.instances[1].end( )

Typical usage: fb.end( ).
To navigate to a page on exit: fb.end( 'somePage.html' ).

fb.activate ( node )

fb.activate crawls a node or a document and assigns actions to elements that are marked up for some kind of floatbox behaviour.
It activates floatboxed anchors, image cycler sets, enhanced tooltips and popup thumbnails.
If you dynamically add floatbox-enabled elements to a page after the initial page load, fb.activate needs to be run against the new content to attach floatbox behaviours to it.
Until activated, a floatboxed anchor will open just like a normal link and the browser will navigate to the href'd page.
If fb.activate's optional node parameter is not provided, the entire document will be crawled.

The easiest way to fetch and add new content is with the floatbox library function fb.ajax, described below.
When you use this function with its updateNode parameter, fb.activate will be automatically run against that node for you.

For any other method of dynamically adding new floatbox content, your code will have to invoke fb.activate after the new content is in place (or, alternatively, have an onclick action of onclick="fb.start( this ); return false;" assigned).
See the section about dynamically loading floatbox content in the instructions for examples of using fb.activate with traditional ajax calls, jQuery and ASP.NET UpdatePanels.

(For legacy code support, the deprecated functions fb.activateElements and fb.tagAnchors are still available and still work as aliases for fb.activate.)

fb.ownerInstance ( node )

ownerInstance accepts a DOM node or an id string and returns the floatbox instance (if any) that owns or contains the passed node.
If the referenced node is not in a floatbox, ownerInstance returns null.
The ability to determine the ownerInstance of a node can be handy when multiple floatboxes are open and you want to execute an API action against a particular instance.

Example - Close the floatbox that contains a node with an id of 'myForm':
fb.end( fb.ownerInstance( fb.$( 'myForm' ) ) );

fb.resize ( width, height, instance )

Resizes a floatbox instance to the new requested dimensions.
Width and height are the new content dimensions in pixels, not including the box decoration around the content.
If neither width nor height are given, or are both passed as 0, the current box content will be measured and the floatbox height will be resized to the current content's height.
If either width or height is 0 or not provided, but the other dimension is given a positive value, the 0 dimension will retain its original value while the positive dimension will be set as requested.
To request a specific width and a remeasure of the height, pass -1 for the height.

If multiple boxes are open, a particular box can be targeted for resizing by passing the floatbox instance object or its instance number as the third parameter. If no instance parameter is provided, the clicked box will be resized if the call resulted from a user click action, otherwise the top box (fb.topInstance) will be resized.

Examples:
If the html content in a floatbox has just been dynamically changed in some fashion, the box can be resized to the same width and the new content's height with a simple call of fb.resize( );
A specific new width combined with a re-measure of the height can be requested with fb.resize( 350, -1 ); With multiple floatboxes, the second instance can have its height measured and resized with either fb.resize( 0, 0, 2 ); or fb.instances[2].resize( );

fb.reload ( source, instance )

Reloads the content in an already running box.
Only content of types iframe, image and ajax can be reloaded. Inline, media and direct content cannot be.
The optional 'source' parameter is a URI path to new content that can replace current box content of the same type without altering or resizing the existing box. Standard usage leaves the 'source' parameter empty thereby causing the existing content to be re-fetched.
If multiple boxes are open, a particular box can be targeted for the reload by passing the floatbox instance or its instance number as the second parameter.
If the 'instance' parameter is not provided, the targetted floatbox instance will be the one the user clicked in to invoke the fb.reload() call, or else fb.topInstance.

The 'reload' function is also available directly on each instance. For example: fb.instances[1].reload( ) will have the same effect as fb.reload( null, 1).

fb.goBack ( instance )

If a previous item has been displayed in a floatbox instance (either because a gallery set is running or content has been updated with either fb.reload or by fb.start combined with the sameBox:true option) fb.goBack will reload the item displayed immediately prior to the current item.
If the optional 'instance' parameter is not provided, the targetted floatbox instance will be the one the user clicked in to invoke the fb.goBack() call, or else fb.topInstance.

The 'goBack' function is also available directly on each instance. For example: fb.lastInstance.goBack( ).

fb.cycleStop ( )
fb.cycleGo ( )

Suspends and resumes all cycler thumbnail and image sets on a page.

fb.pause ( bool, instance )

fb.pause( true ) pauses a running slideshow and fb.pause( false ) resumes a paused one.
As with many of the other API calls, when multiple floatbox instances are present fb.pause will default to the clicked instance or to fb.topInstance, and the pause function is available directly on each instance object.

fb.showItem ( index, instance )

Displays item number 'index' from a currently loaded gallery set. The first item in a set has an index of 0.
With multiple concurrent floatboxes, the default instance will be the clicked floatbox or fb.topInstance.
The showItem function is also available directly on the individual instance objects. For example:
fb.showItem( 3 ) and fb.topInstance.showItem( 3 ) are equivalent.

Back to Index

Event Callbacks

Floatbox will look for callback functions that you define for the following events:
beforeBoxStart, afterBoxStart, beforeItemStart, afterItemStart, beforeItemEnd, afterItemEnd, beforeBoxEnd, afterBoxEnd, afterResize, beforePrint, afterPrint, afterFBLoaded.

Javascript code is assigned to options of those names in the standard options setting manner of putting them in fbPageOptions or on an anchor's rev or data-fb-options attribute.
Callbacks defined in a page's fbPageOptions definition can be either true javascript functions or strings to be eval'd.
By their nature, callbacks defined as options in an anchor's rev tag will be strings and so will be eval'd.

If any of the before* callback functions return a value of false, the associated Floatbox action will be cancelled.
This applies only to callbacks defined as true functions. Eval strings cannot cancel Floatbox actions.

Example - A function callback in the page options: function myFunc() {
  alert( 'eat a peach' );
  return true;
}
fbPageOptions = {
  beforeBoxStart: myFunc
};

And a string callback in an anchor's data-fb-options (or rev) attribute: <a href="xyz.php" class="floatbox" data-fb-options="afterItemEnd:`myFunc();`">talk about fruit</a>
(Don't forget the back-quotes. They're required for correct parsing.)

afterFBLoaded can be considered deprecated but is still available. Use fb.DOMReady( function ) for cross-browser DOMContentReady invocation.

Back to Index

Library Functions

In addition to the floatbox functions described above, the fb object exposes a comprehensive set of functions that allow you to use floatbox as a javascript library.
The floatbox library is a robust and correct collection of functions that make it easy to manage ajax, flash, events, forms, DOM interactions and many other operations simply and reliably across all client browsers.

Note: All library functions that have a 'node' parameter will accept either a DOM element or the id string for an element as that parameter.

fb.$ ( id )

The fb.$ function is short-hand for 'document.getElementById', with minor extensions.
If the id parameter is a string, it will return the element that has that id, or null if there is no such element.
If the id parameter is already an element, that element will be returned.
If a match is not found on the current document, each floatbox instance will be searched.
This function can also be invoked as 'fb$()', without the dot, for historical reasons.

fb.DOMReady ( func )

Use fb.DOMReady to register a function to be called when (or after) a document's DOM is fully loaded but before window.onload fires. The single parameter is a function to be exectured at DOMContentLoaded time.
The fb.DOMReady function supports all browsers, including older versions of IE that do not have built-in support for DOMContentLoaded.

Note that fb.addEvent can also register a DOMReady function with fb.addEvent( document, 'DOMContentLoaded', func ). The difference is, fb.addEvent will not fire the function if it is registerd after DOMContentLoaded has occurred and will not register duplicates of a function, whereas fb.DOMReady will immediately execute the passed function if it is called after DOMContentLoaded and will be happy to execute the same function as many times as requested.

fb.addEvent ( node, action, func )
fb.removeEvent ( node, action, func )
fb.removeEvent ( obj )

These two functions standardize DOM2 event handling across different browsers, removing most of the troublesome characteristics of IE's event handlers.
All parameters are required.
The 'node' parameter is the element (or its id) to attach (or detach) the event handler to.
The 'action' parameter is the event you want to target and does not include the 'on' prefix used by IE (e.g., use 'load' and not 'onload').
The event handler code is passed as a function in the third parameter.
Using fb.addEvent in Internet Explorer adds the following enhancements to IE's event handling to make it more similar to standards-based DOM2 events:

The return value for fb.addEvent is a js object that can be passed to fb.removeEvent to detach the assigned event handler. Retaining this value for future event removal helps minimize memory leaks in IE.

Example: x = fb.addEvent ( 'someId', 'click', function ( e ) {
  alert ( 'type of element clicked: ' + e.target.nodeName );
} );
fb.removeEvent ( x );

fb.addEvent and fb.removeEvent can also be used to assign and remove DOM0 events by having the action parameter begin with 'on'. For example, fb.addEvent ( someNode, 'onclick', someFunc ) will assign a DOM0 click action equivalent to someNode.onclick = someFunc. The return value is still a javascript object that can be passed to fb.removeEvent.

fb.stopEvent ( e )

fb.stopEvent is a cross-browser way to stop normal execution, including bubbling and propagation, of an event.
Pass the event you want to block as the only parameter.
stopEvent's return value is always a boolean false that can be passed through by your calling function.
For example, to stop the default click behaviour in the example above for addEvent, we would make our click function would look like this:
function( e ) { alert( ... ); return fb.stopEvent( e ); } )

fb.extend ( objTarget, objSource [, objSource2 ...] )

fb.extend takes two or more javascript objects as parameters and extends the properties and values of the first object with those from the other objects.
The target object is modified in place and is also the return value of the function.
If passed only a single object in the parameters, fb.extend will return a duplicate copy of that object.
fb.extend( myObj, yourObj ) will copy yourObj's name:value pairs into myObj.
ourObj = fb.extend( {}, myObj, yourObj ) returns a new merged object without modifying myObj.
newObj = fb.extend( oldObj ) returns a new object seeded with name:value pairs from oldObj.

fb.executeJS ( strURI, callback )

Use fb.executeJS to dynamically load and execute an external javascript file.
The javascript file can come from any domain (cross-domain scripting restrictions are not in effect).
The optional callback function will be fired after the external javascript has completed execution.
fb.executeJS can be useful for loading javascript files in a document after the page has been rendered. It is also a good mechanism for fetching JSONC/JSONP data or loading API services such as those from Google Code.
For example, Google's translation widget can be dynamically added to a page with something like <script>
  function init() { ... }
  fb.executeJS( "//translate.google.com/translate_a/element.js?cb=init">
</script>

fb.getFormValues ( source )

Returns an associative array of all the name:value pairs for the elements of a form.
The source parameter can be a form DOM element, a form's name, or a form's id.
The getFormValues function provides correct form handling as per the W3C forms recommendations and properly handles empty and missing values, radio buttons and user defined input types.
The following input element types are ignored: file, image, reset, submit and button.

fb.serialize ( source )

serialize returns a properly encoded string of name=value pairs that can be used as a URI's querystring or for submission by an AJAX POST call.
The source parameter accepts any of an associative array, a form DOM element, a form's name, or a form's id.
If a form is passed as the source, the values are first parsed out using getFormValues and the result of that is serialized.

fb.deserialize ( str )

deserialize reverses the serialize function by taking an encoded parameter string as its argument and returning an associative array of decoded name:value pairs.

fb.preload ( src, callback )

You can borrow floatbox's image preloader if you like. Pass fb.preload the source path for the image to preload as a string. Or, pass an array of source path strings for images to be preloaded.
If the optional callback function is provided as the second parameter, that function will be invoked when the image preload completes.
The callback function can accept a single parameter that will be the unattached img element containing the preloaded image.
If src is an array, callback is called after the last image loads.

fb.printNode ( node, style )

Use printNode to display a print dialog to your users that will print only the contents of a particular node, rather than printing the full page.
The printNode function accepts two arguments, both of which are optional.
The node parameter accepts either a DOM node or an element's id string. If node is null, the contents of fb.topInstance.fbContent will be printed.
You can apply styles to the print node's content using the optional style value. 'style' can be a string of css definitions (like you would place directly in an element's style attribute), or can be the path to a css file that contains the css definitions to be applied.

fb.getElementsByClassName ( className[s], node )

Returns an array of elements within 'node' that have a class name of 'className'.
The className parameter can be a simple string or an array of strings. If an array, all elements that have any of the requested classNames will be returned.
The 'node' parameter is optional and will default to the <html> element if not given.

fb.getStyle ( node, property, integerize )

Returns the cascaded or computed (currently active) style for a given element.
The optional 'property' parameter is any css property. You can use either the css or camelCase property syntax (i.e., 'font-size' or 'fontSize').
If 'property' is not passed, the return value will be a cssText string of all effective styles for the referenced node in the form 'property1: value1; property2: value2;...propertyN: valueN;'.
If the 3rd parameter is 'true', the return value will be an integer. E.g., a style of '49px' will come back as the number 49. Example: size = fb.getStyle( 'someId', 'font-size' )

fb.getScrollLeft ( )
fb.getScrollTop ( )

Returns the browser's current horizontal or vertical scrollbar position in pixels.

fb.getScroll ( )

fb.getScroll combines getScrollLeft and getScrollTop into a single call with a return value of an associative array containing the two named values 'left' and 'top'.
Example usage: var scroll = fb.getScroll( );
alert( 'horizontal scroll is ' + scroll.left + ' pixels' );
alert( 'vertical scroll is ' + scroll.top + ' pixels' );

fb.getViewportWidth ( )
fb.getViewportHeight ( )

Returns the browser's current viewport width or height in pixels.

fb.getViewport ( )

fb.getViewport combines getViewportWidth and getViewportHeight into a single call with a return value of an associative array containing the two named values 'width' and 'height'.
Example usage: var viewport = fb.getViewport( );
alert( 'browser screen is ' + viewport.width + ' wide and ' + viewport.height + ' high' );

fb.getLayout ( node, local )

Use getLayout to get the position and dimensions of any node on your page.
getLayout accepts a DOM node or an element's id string and returns an associative array containing the values 'left', 'top', 'width' and 'height'.
If the optional second parameter is true and node is inside an iframe, the returned 'left' and 'top' coordinates will be relative to that iframe's document, otherwise the coordinates are relative to the top page's document.

fb.getIframeDocument ( node )
fb.getIframeWindow ( node )

These functions return an iframe's document object and window object respectively.
'node' is an optional parameter. If provided, it must be an iframe element or the iframe element's id. The iframe does not have to be inside a floatbox.
If 'node' is not passed, the fbContent element for the clicked floatbox or for fb.topInstance will be used.

Null is returned if node is not an iframe and no floatboxed iframe could be found using the defaults as described above.

The getIframe* functions are also available on individual floatbox instances. For example, calling fb.getIframeDocument( ) is the same as calling fb.topInstance.getIframeDocument( ).

A simple example; get the window object of the iframe in the only running floatbox:
win = fb.getIframeWindow( ).

fb.nodeContains ( parentNode, childNode )

fb.nodeContains returns true or false based on whether the DOM element 'childNode' is contained inside the 'parentNode' element.
Both parentNode and childNode are mandatory arguments and can be either the actual DOM element or a string id value that identifies the element.
If parentNode and childNode are the same node, true is returned.
fb.nodeContains will 'see through' iframes. That is, if childNode is inside an iframe and that iframe is inside parentNode, fb.nodeContains will return true.

fb.hasAttribute ( node, attribute )

Returns true or false based on whether the DOM element 'node' has 'attribute' set in its tag.
If the node's attribute is set to an empty string, the function still returns true.
The node parameter can be a DOM element or the string id of an element.

fb.getOuterHTML ( node )

Not all browsers support the outerHTML property. fb.getOuterHTML will return the outerHTML (innerHTML plus the element's own markup) for any element in all browsers.

fb.setInnerHTML ( node, html )

This is a safe way to assign innerHTML to any element. It works reliably on both text/html and application/xhtml-xml pages.
The 'html' parameter is optional and defaults to the empty string. Applying the empty string clears node of all its existing innerHTML.
If direct assignment of innerHTML works, it is used (it's a lot quicker). If setting of innerHTML is rejected, DOM insertion methods are used.

fb.encodeHTML ( html )
fb.decodeHTML ( html )

fb.encodeHTML takes a string and returns that string with all & < > and " characters encoded to &amp; &lt; &gt; and &quot;.
fb.decodeHTML reverses that process and also decodes &apos; to a single quote and decodes numbered entities like &#222; to their character equivalents.

fb.typeOf ( thing )

The fb.typeOf extends javascript's builtin 'typeof' operator by resolving ambiguous 'object' return values and handling window objects.
The return value will be one of 'number', 'string', 'boolean', 'object', 'array', 'function', 'undefined', 'null', 'node' or 'window'.
Note that IE (all versions) has major problems handling dynamically created and destroyed windows inside iframes. fb.typeOf will detect a tomb-stoned window in IE and return a value of 'null' for it.

fb.forEach ( object, function )

Use fb.forEach to execute a function against each member of an associative array (javascript object). The function takes two parameters which will receive the 'name' and 'value' for each entry in the object.
Example: fb.forEach( myObject, function( key, val ) {
  alert('name: ' + key + ', value: ' + val);
} );

fb.flashObject ( {
     source: strURI,
     width: numPixels,
     height: numPixels,
     params: { name: value [, name: value] } | strOptions,
     node: node | id,
     id: string,
     altContent: strHTML,
     minVersion: strVersion
} )

fb.flashObject is a full-featured, but simple to use, script component that adds flexible cross-browser flash objects to your page.
Because the flash objects are created from external script they will not be subject to Firefox and Opera's annoying (and inconsistent) "click to activate" behaviour.
fb.flashObject supports alternate content, Flash version checking and provisioning of all Flash parameters.

A simple example: fb.flashObject( {
    source: 'somePath.swf',
    width: 400,
    height: 300,
    altContent: '<img src="someImage.jpg" />'
} );

fb.ajax ( {
     source: strURI,
     updateNode: node,
     postData: form | formID | formName | object | string,
     success: function( xhr ),
     failure: function( xhr ),
     finish: function( xhr ),
     timeout: msecs,
     cacheable: boolean,
     async: boolean,
     headers: { name: value [, name: value] }
} )

The fb.ajax function is an XMLHttpRequest object wrapper that provides AJAX functionality for dynamic content and data fetches using a simple and flexible function call. Both GET and POST requests are supported, a page element can be updated directly with the returned content, callback functions are available for more complex handling requirements, and both synchronous and asynchronous calls are supported.

Here's an example that updates the contents of a div called "contents" and puts the time of the update into a span element using Floatbox's ajax support:
<script type="text/javascript">
  // this is the callback function that will be used to add the update time to the page
  function updateTime( xhr ) {
    fb.setInnerHTML( 'time', (new Date()).toTimeString() );
  }
  // this is the onclick action that will fire the ajax request
  function click( ) {
    fb.ajax({ source: 'ajax.php', updateNode: 'contents', success: updateTime });
  }
</script>

<input type="button" onclick="click();" value="get ajax" />

<div id="contents"></div>
last update at: <span id="time"></span>

Back to Index