Floatbox v4.18 - Programmer's API Reference

randomous.com

Index

* Functions marked with an asterisk are available immediately while the page is loading.
The other functions are available at DOMContentLoaded (which equals afterFBLoaded).

Variables and Properties

fb

Floatbox's primary object is the global var "fb".
All properties and functions are members of the fb object.

If you are running floatbox in a hierarchy of iframes, the fb objects in each child window are references to the fb object on the top document (i.e., there is only one fb object even though there are multiple window objects).
An iframe displayed by floatbox that does not have floatbox.js included on its document will not have the global fb var in its window's scope. To programmatically use fb from such a child iframe, fetch it from the parent window by referring to it as "parent.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].

fb.lastChild

fb.lastChild always points to the last box loaded.
If there is only one box (or none displayed yet), fb.lastChild === fb.
fb.lastChild is always identical to fb.instances[fb.instances.length-1].

fb.topBox

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

fb.parent

For any given box, .parent points to the box immediately preceding it in the instances array. For example, if 3 boxes are stacked up, fb.lastChild.parent will point to the middle box.
fb.instances[2].parent === fb.instances[1].
fb.parent (fb always being the primary, first-loaded box) is identical to fb.

fb.fbContent

fbContent is the DOM node (element) holding the content that is displayed by 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 'lastChild', 'topBox', or the 'instances' array of pointers to get to the fbContent element for secondary (stacked) floatboxes - e.g. fb.topBox.fbContent or fb.instances[2].fbContent.

fb.currentIndex

In a multi-item gallery set, fb.currentIndex is the zero-based index of the currently showing item in the set array. For example, if item 4 of 7 is showing, fb.currentIndex is 3.

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 backward-compatabiltiy, fb.start still accepts the old-school 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.activateElements().
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 'arg' is not provided, fb.lastChild - the last opened box - will be closed.
Typical usage: fb.end( ).
To navigate to a page on exit: fb.end( 'somePage.html' ).

fb.activateElements ( node )

fb.activateElements 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.activateElements needs to be run against the new content to activate it.
Until activated, a floatboxed anchor will open just like a normal link and navigate the browser to the href'd page.
If the 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, activateElements 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.activateElements after the new content is in place.
See the section about dynamically loading floatbox content in the instructions for examples of using fb.activateElements with "normal" ajax calls and ASP.NET UpdatePanels.
(The legacy function fb.tagAnchors still works and is now an alias for activateElements.)

fb.restack ( instance )

If multiple non-modal boxes are open, fb.restack can move a particular box instance to the top making it appear above the other boxes.
The 'instance' parameter is optional and can be an instance number or the actual floatbox instance object.
If 'instance' is not provided, the called floatbox will be the one moved to the top.
For example, the following three calls are equivalent:
fb.restack( 2 );
fb.restack( fb.instances[2] );
fb.instances[2].restack( );

fb.ownerInstance ( node )

ownerInstance accepts a DOM node or an id string and returns the instance number of the floatbox that owns or contains the passed node.
The first floatbox instance is 0.
If the node is not in a floatbox (i.e., it is on the base page), ownerInstance returns -1.
ownerInstance is the index into the fb.instances array.
This index is needed when working with multiple non-modal boxes to locate a particular box for an action such as bringing the box to the top or closing it.
Example - Bring the non-modal box that contains the node with id 'myForm' to the top (assuming the content type is not iframe but is one of ajax, direct or inline):
fb.restack( 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 +ve value, the 0 dimension will retain its original value while the +ve dimension will be set as requested.
If multiple boxes are open, a particular box can be targeted for the reload by passing the floatbox object or its instance number as the second parameter. If no instance parameter is provided, the top box will be resized.
For example, if the html content in a floatbox has just been dynamically changed in some fashion, the box can be resized to the new content's height with a simple call of fb.resize( );

fb.reload ( source, instance )

Reloads the content in an already running box.
The optional 'source' parameter is a URI path to new content that will replace the current box content. If 'source' is not given, the existing content will be re-fetched.
If multiple boxes are open, a particular box can be targeted for the reload by passing the floatbox object or its instance number as the second parameter.
Only content of types iframe, image and ajax can be reloaded. Inline, media and direct content cannot be.

fb.goBack ( )

If a previous item has been displayed in the top-most running box, either because a gallery set is running or content has been updated with either fb.reload or fb.start and sameBox:true, fb.goBack will reload the item displayed immediately prior to the current item.

fb.cycleStop ( )
fb.cycleGo ( )

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

fb.pause ( bool )

fb.pause( true ) pauses a running slideshow and fb.pause( false ) resumes a paused one.

fb.showPrevious ( )
fb.showNext ( )

Displays the previous or next item in a gallery set (group) of items. If you're already showing the first or last item in a set, wrap behaviour is determined by the 'enableWrap' option.

fb.showItem ( index )

Displays item number 'index' from a currently loaded gallery set. The first item in a set has an index of 0.

Back to Index

Event Callbacks

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

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.
Be careful when using an eval'd string as a before* callback because the return value will be the value of the last statement executed.
So an eval'd callback function of "abc = 42; xyz = false;" can cancel a floatbox action whereas "xyz = false; abc = 42;" will not.
It's cleanest and safest if your eval'd statement is a simple call to a proper javascript function defined elsewhere on the page.

The afterFBLoaded callback is a handy place to put code to run at page startup.
When the callback fires, the DOM has completed loading and Floatbox has activated all its content on the page, but window.onload has most likely not yet fired.
Use afterFBLoaded as your DOMContentLoaded hook.

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.)

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 an element, that element will be returned.
(Note that the function name is fb$, NOT fb.$ with a dot.)

fb.flashObject ( url, width, height, params, node, id, altContent )

Use this to easily add simple 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.
If you need flash version detection, consider using swfobject2 instead.

An alternate way to call this function is to pass parameters as members of a single javascript object (associative array). For example: fb.flashObject( {
    url: 'somePath.swf',
    width: 400,
    height: 300,
    altContent: '<p>Flash required to view this content.</p>'
} );

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

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 is always the passed 'func' parameter, which can be used to track assigned events for future removal.
Example: fb.addEvent( 'someId', 'click', function(e) { alert( 'type of element clicked: ' + e.target.nodeName ); } )
fb.addEvent makes document.DOMContentReady available in all broswers including IE. fb.addEvent( document, 'DOMContentLoaded', func );

fb.stopEvent ( e )

fb.stopEvent is a cross-browser way to stop normal execution (bubbling, 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.
To obtain an extended copy of the the original target without modifying it, pass an empty object as the first parameter and the target object as the second.
fb.extend( myObj, yourObj ) will copy yourObj's name:value pairs into myObj.
var ourObj = fb.extend( {}, myObj, yourObj ) returns a new merged object without modifying myObj.
var newObj = fb.extend( {}, oldObj ) will create 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.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 querystring 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 currently displayed floatbox contents 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, node )

Returns an array of elements within 'node' that have a class name of 'className'.
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: var size = fb.getStyle( 'someId', 'font-size' )

fb.getScroll ( )

Returns the browser's current scroll-bar positions in pixels.
Return value is an associative array with named values of 'left' and 'top'.
Example usage: var scroll = fb.getScroll( );
alert( 'horizontal scroll is ' + scroll.left + ' pixels' );
alert( 'vertical scroll is ' + scroll.top + ' pixels' );

fb.getDisplayWidth ( )
fb.getDisplayHeight ( )

Returns the current browser screen width or height in pixels.

fb.getDisplaySize ( )

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

fb.getLayout ( node )

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'.
The 'left' and 'top' positions are relative to the base page document.
If node is inside an iframe, the coordinates are not those of the iframe's window, but will be translated to the coordinates of the containing page.

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 node. The iframe does not have to be inside a floatbox.
If node is not passed and the called floatbox instance contains an iframe as its content, the document or window for that instance's iframe will be returned.
For example, calling fb.instances[2].getIframeDocument( ) is the same as calling fb.getIframeDocument( fb.instances[2].fbContent ).
If node is not passed and the called floatbox instance does not contain an iframe, fb.lastChild.fbContent is assumed and the document or window object for the last-loaded iframe is returned.
Null is returned if node is not an iframe and no floatboxed iframe could be found using the above described defaults.
A simple example; get the window object of the iframe in the only running floatbox:
var win = fb.getIframeWindow( ).

fb.nodeContains ( parentNode, childNode )

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.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.
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.translate ( source, destLang, callback, plainText )

The fb.translate function is a wrapper for the translate capability of the Google AJAX Language API. Its use is subject to Google's terms of use. Do not use this function if you don't agree with or abide by those terms of use.
All parameters are optional.

Important Notes:

Here's a basic example that will translate floatbox content to the site visitor's current browser language when the item is opened: <a href="#someID" class="floatbox" data-fb-options="afterItemStart:`if (fb.language != 'en') fb.translate();`">click me</a>

And another example that translates the hidden div content at page load time before the item is shown in floatbox. <script type="text/javascript">
fbPageOptions = {
    afterFBLoaded: function() {
        if (fb.language != 'en') fb.translate('someID');
    }
}
</script>

And a translation of direct text to a specific language, using the callback to access the results. fb.translate('eat a peach', 'fr', function(result) { alert(result.responseData.translatedText); });

fb.ajax ( { source: strURI, updateNode: node, callback: function(xhr), postData: form|object|strParams, cache: boolean, headers: { name: value [, name: value] } } )

The fb.ajax function is an XMLHttpRequest object wrapper that provides AJAX functionality for dynamic gets and posts using a single line of script.
The return value is the XMLHttpRequest object. Having access to this object enables use of the object's native properties and methods such as 'abort()'.
fb.ajax always issues asynchronous requests.

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', callback: updateTime });
  }
</script>

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

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

Back to Index