Programmer's API Reference

For the current version 7.3.
For other versions, see the docs in the download package.

Index

Functions

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, context boxes and popup thumbnails.

After dynamically adding floatbox-enabled elements to a page at some time other than initial page load, run fb.activate() to 'light up' that new content. Until activated in some manner, floatbox elements on the page will not have behaviours attached and the links will open just like normal links with the browser navigating to the href'd page.

fb.activate's 'node' parameter is optional. If provided, it should be a node's id or the node object itself that contains the elements requiring activation. If the node parameter is not provided, the entire document will be re-scanned.

The easiest way to dynamically fetch and add new content to a page is with the floatbox library function 'fb.ajax', described below.
When this function is used with its '$' (or 'updateNode') parameter, fb.activate() will be automatically run against that node.

For any other method of dynamically adding new floatbox content, the code that brings in the content should invoke fb.activate() after the new content is in place or. Alternatively, new floatbox links could 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.

fb.start ( source[s], options )

fb.start creates and invokes a floatbox.

The source parameter references the content to be shown and can be of a variety of types: a URI string (path to the content), a DOM element, an element's id, or a string of HTML. It can also be an array of these things to start a gallery set of multiple items.
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 (javascript object) of option name:value pairs.

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' } );

Show a series of videos.

fb.start( [ 'chapter1.mp4', 'chapter2.mp4', 'chapter3.mp4' ], { doSlideshow: true } );

Launch an existing anchor in floatbox. Pass anchor's id, or the actual element itself, to fb.start().

fb.start( 'someAnchorId' );
or
var myLink = fb.$('someAnchorId'); fb.start( myLink );

Open inline hidden div content.

fb.start( '#someDivId' );
or
var myHiddenDiv = fb.$( 'someDivId' ); fb.start( myHiddenDiv );

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>
An anchor started directly in this manner does not need a floatbox class and does not have to be activated by fb.activate().

fb.end ( arg )

Call fb.end() to close a running floatbox.

The 'arg' parameter is optional and is overloaded in terms of functionality.
If 'arg' is a boolean value of true and multiple floatbox instances are currently open, all instances will be closed.
A function passed in as 'arg' will be called when the ending animations complete, right after afterBoxEnd if that is set.
If 'arg' is a string it 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 list.
(See the Multiple Floatboxes section for how to close a specific floatbox when more than one is open.)

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

fb.resize ( metrics, callback, animationTime )

Resizes and/or repositions an open floatbox.

metrics is a javascript object that contains any or all of 'left', 'top', 'width' and 'height' properties. The 'left' and 'top' properties set the position of a floatbox's outer corner, while 'width' and 'height' specify the dimensions of the content area. All four values can be specified as numeric pixel values or 'xx%' for a percentage of the screen size.
If a metrics property is assigned boolean true, that dimension will not change and will remain at its current size or position while the other dimensions are set or recalculated.
If any property is not present (or is set to an unrecognizable value), that metric will revert to its initial calculated or assigned value when the floatbox was first created, subject to any stickyMove or stickyResize adjustments in play. (See the Options Reference for information about the stickies.)
For proportional content (images, video, anything where height was set as "__%w"), if only one of width or height is provided in metrics, but not the other, the other will be adjusted such that proportionality will be maintained.

callback is a function (or an executable javascript string) to be run when the resizing animation completes. If a true function, it will be passed the current floatbox instance object as its only parameter.

The speed of any animated resizing or relocation of a resized floatbox is determined by the resizeTime option. That setting can be overridden in any fb.resize() call by passing the target animation time in seconds to the animationTime parameter. Pass in 0 here to temporarily turn off resizing animations and instantly jump the box to it's new size and position.

Examples:
If the html content in a floatbox has just been dynamically changed in some fashion, and a width or height dimension was measured, not assigned in the options, the box can be resized to the new content's size 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( { width: 350 } );
The width can be held at its current value while the height is set to specific value with fb.resize( { width: true, height: 500 } );
The same resizing can be done with a simultaneous positioning of the box snug up against the top-left corner of the screen with fb.resize( { left: 0, top: 0, width: true, height: 500 } );
A floatbox can be remeasured, or revert back to initial width and height, while its current position is held constant and resize animations are disabled with a call of fb.resize( { left: true, top: true }, null, 0 );

fb.reload ( source )

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. To load new content in a floatbox, it's usually best to use the fb.start() function and include the 'sameBox:true' option in that call.

fb.pause ( boolean )

fb.pause( true ) pauses a running slideshow (started with the 'doSlideshow' options) and fb.pause( false ) resumes a paused one.

fb.showItem ( index )

Use showItem to change the currently displayed image in a gallery set to another member of that set.

The index parameter can be a number, or a string of 'next' or 'prev'. If it's one of the strings, a gallery set will show the previous or next item in the set, wrapping around the set ends if necessary.
If a numerical index is provided, the corresponding item from the gallery set will be shown. The first item in a set has an index of 0.
For example: fb.showItem( 3 ) will show the 4th item in a currently displayed gallery set while fb.showItem( 'next' ) will show the next item.

fb.goBack ( )

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.
An example of how this might be used can be found in the news-reader example on the HTML tab of the Floatbox demo page.

Back to Index

Multiple Floatboxes

Multiple floatboxes can be open at the same time, and most of the functions listed above in the 'Floatbox Functions' section (all but activate, and start) act on a single particular floatbox. When the functions are invoked as members of the 'fb' object as shown above, they will apply to the top-most floatbox.

To explicity act upon a particular floatbox, get a reference to the desired floatbox instance using one of the two functions described below, and run the function from that instance.

fb.getInstance ( name )

Use fb.getInstance to retrieve a reference to a particular floatbox instance when more than one is open simultaneously.

Each floatbox instance has a name which can be assigned using the instanceName option. If no name is assigned, the filename (without extension) or the id from the starting item will be used as the name. Retrieve a reference to a particular floatbox instance by calling fb.getInstance with the name of the box.

If the 'name' parameter is not provided, the top-most box from a z-index stacking perspective will be returned, which of course will be the only box if there's only one and will be undefined if there are none.

Here's an illustrative example using a named floatbox instance. Suppose we have a floatbox that opened content from a hidden div with an id of "Info" (e.g., href="#Info"). We can then close that particular floatbox as follows:

var instance = fb.getInstance( 'Info' ); if ( instance ) { instance.end(); }
or simply...
fb.getInstance( 'Info' ).end();
if we're confident the floatbox exists at the time of the call.

We were lazy in that example and just used the name that was picked up in the background from the starting href. To be more clear and obvious in our coding, we probably should have explicitly assigned a name to the box and used that. Like this:

<a href="/path/some_page.html" data-fb-options="instanceName:superBox"></a> <script> var instance = fb.getInstance( 'superBox' ); </script>
(The default instance name in this example would have been "some_page" had we not set instanceName with our own value.)

fb.getOwnerInstance ( node )

getOwnerInstance accepts a DOM node or an id string and returns the floatbox instance (if any) that contains the passed node. If the referenced node is not in a floatbox, getOwnerInstance returns null.

The ability to determine the owner instance of a node can be handy when multiple floatboxes are open and an API action needs to be targetted to a particular instance.

For example, suppose we want to close a floatbox from an onclick action somewhere in its content:

onclick = "fb.getOwnerInstance( this ).end( );"

{instance}.fbContent, etc.

Each major component element of a floatbox is accessible as a named property of the box's instance object. The most useful such property is {instance}.fbContent, which is the DOM node (element) holding the content that is displayed by a floatbox - an img, iframe, or div depending on what kind of content is currently showing.
Having this reference can be helpful when dynamically working with floatboxed iframe or other html content.

For example, if we have only one floatbox currently showing, and it contains iframe content, we can reference the iframe's document like this:

instance = fb.getInstance(); if ( instance ) { contentDoc = instance.fbContent.contentWindow.document; }

It would be safer, and probably a better coding practice, to use a named instance and reference it with something like fb.getInstance( 'name' )

Many other floatbox component nodes can be similarly accessed. For example, the caption can be reached through the instance.fbCaption reference.

Back to Index

Library Functions

In addition to the floatbox functions described above, the fb global object exposes a comprehensive set of functions that allow use of floatbox as a javascript library.
The floatbox library is a robust and correct collection of functions that make it easy to manage ajax, events, script loading, forms, flash, 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, doc )

The fb.$ function is short-hand for 'document.getElementById', with additional behaviour.

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.
The optional 'doc' parameter is for iframe environments and is a specific document element on which to look for the requested id.
If no 'doc' parameter is passed, each document in a heirarchy of same-domain iframes that have the floatbox code installed will be searched for the requested element, starting with the top (base) document.

fb.addClass ( node[s], className[s] )

Use addClass to assign one or more class names to one or more document nodes (elements). The node parameter can be a node reference, a node's id, or a CSS selector string, and can be an array of those things for multiple assignments in one call. Multiple classes can be assigned in one go by passing an array of class names as the className parameter, or with a string containing multiple names separated by spaces.

fb.addEvent ( node[s], action[s], func )
fb.removeEvent ( node[s], action[s], func | obj )

These two functions standardize DOM2 event handling across different browsers, removing most of the troublesome characteristics of older IE's event handlers.

All parameters are required.
node is what the event handlers will be attached to (or detached from), and can be an element id, a css selector string, or an array of those things.
The action parameter is the name or names of the event(s) to be handled. Use an array of names to specify more than one event name.
For DOM2 events, do not include the 'on' prefix (e.g., use 'load' and not 'onload'). Attach DOM0 event handlers by including the 'on' prefix in the event name (e.g., 'onload').
The event handler code is passed as a function in the third parameter.
Using fb.addEvent standardizes both DOM0 and DOM2 event handling across all browsers (including old Internet Explorer) to align with DOM2 event standards by ensuring the following:

The return value for fb.addEvent is an array that can be passed to fb.removeEvent to detach the assigned event handlers.
Example:

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

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

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 and callback functions can be assigned which receive the details of the fetched results (including JSON if appropriate).

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> // callback function to add the update time to the page function updateTime () { fb.setInnerHTML( 'time', ( new Date() ).toTimeString() ); } // onclick action that fires the ajax request function click( ) { fb.ajax( { source: 'ajax.php', $: 'contents', success: updateTime } ); } </script> <input type="button" onclick="click();" value="get ajax" /> <div id="contents"></div> last update at: <span id="time"></span>

fb.animate ( props, callback, duration, inflection, easing, monitor )

fb.animate provides versatile and smooth animation of single or multiple properties of single or multiple document elements, and will group those animations such they will occur as a unit and complete simultaneously.

props describes the elements, properties and values that are to be animated. The basic props data structure is a javascript object with a mandatory '$' property identifying one or more elements, together with any number of property:value pairs identifying the individual components to animate.
The '$' value can be an element reference, an element's id, an array of references and/or ids, or a CSS selector string.
The property values to be animated must be numeric. Starting values are whatever the properties are set to at the time fb.animate is called.
e.g.

{ $: 'myDivId', left: 55, width: 555 }

Pass an array of such objects as the first function argument to include multiple elements in the animation.

callback will be executed when the animation completes. It's a good place to launch a second animation if doing a series of sequential animations, or to continue with some other script actions.

duration is the time taken by the animation. It can be provided as milliseconds or seconds. A duration number less than 77 is taken to be seconds, 77 and above are milliseconds.
Durations provided as seconds are approximate. Small animations will move slower but finish earlier and large animations will move more quickly but still take a little longer. Using milliseconds specifies exact duration.

By default, animations are eased, with a slower start, quicker middle, and slow again to finish.

easing modifies the strength of those speed changes. A value of 1 sets a linear animation with no speed changes. The default of 2.5 makes the animations a little more gentle with a slower launch and landing. Larger values give more dramatic easing, and values less than 1 give strange reverse fast-slow-fast easing.

inflection modifies where the transition from acceleration to deceleration occurs. It is a value between 0 and 1, with the default of 0.5 putting the transition right in the middle of the animation. 0 puts the transition right at the beginning which makes the animation start fast and slow down continuously until completion. 1 starts slowly and end quickly, and values in between move the transition point of the slow-fast-slow animations to the specified portion of the duration.
The default easing and inflection values can be set in the 'global' section of fbOptions and are 2.5 and 0.5 respectively if not set or specified.

monitor is a little complicated, but can be quite useful for fine control of and response to animation progress. Pass an empty javascript object {} to share information with the animation routine.
This object will be kept current with 'step'values (a number between 0 and 1). The 'step' value is writable and the animation can be made to immediately jump to completion by setting monitor.step = 1.
Another writable property is called 'active'. An animation can be temporarily paused, or frozen, by setting monitor.active = false, and resumed at any time later by setting monitor.active = true.

Alternatively, monitor can be a function, and this function will get called at every step in the animation. One parameter is passed to the monitor function: the javascript object described immediately above. The monitor function can manipulate the animation in the same ways of setting .step and .active, and it can also initiate new actions at any point in the animation - perhaps launching something when the animation step goes past the half way point, for example.

Note that elements can be scrolled with animation using the pseudo property names 'scrollLeft' and 'scrollTop', including scrolling the page by referencing the window or document as the animated element.

fb.attr ( node[s], name, val )

Reads, sets, or removes an attribute from an element.

The node parameter can be an element reference, an element's id, a CSS selector string, or an array of any of those.
Pass null to the val parameter to remove the named attribute. If val is not provided (is undefined), fb.attr will return the current value of the named attribute, or the null value if the attribute is not present. If val is neither null nor undefined, the named attribute will be assigned the passed value. The attribute will be created if it is not already present.
To set (or clear) multiple attributes at once, a javascript object can be passed as the second parameter with the object holding multiple name:value pairs, in which case the val parameter is ignored.

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.deserialize ( str )

deserialize reverses the serialize function by taking an encoded parameter string as its argument and returning an associative array (javascript object) of decoded name:value pairs.
The passed string is first run through fb.decodeHTML to translate encoded HTML entities such &amp; into their corresponding simple characters.

fb.docReady ( func )

Use fb.docReady to register a function to be called as soon as possible after a document's DOM is fully loaded and ready for interaction.

The single parameter is a function to be exectured at DOMContentLoaded time.
The fb.docReady function supports all browsers, including older versions of IE that do not have built-in support for DOMContentLoaded.

In just about all cases, it's better to use fb.ready rather that fb.docReady. fb.ready ensures that everything in the Floatbox code is ready for use, and ensures that the document is ready.

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

Merges and duplicates javascript objects.

fb.extend takes any number of 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( thisObj, thatObj ) will copy thatObj's name:value pairs into thisObj.
newObj = fb.extend( {}, thisObj, thatObj ) returns a new merged object without modifying thisObj.
newObj = fb.extend( oldObj ) returns a new object seeded with name:value pairs copied from oldObj.

fb.flashObject ( { source: strURI, $: node | nodeID, width: numPixels, height: numPixels, params: { name: value [, name: value] } | strOptions, id: string, success: function, failure: function } )

A full-featured, but simple to use, script component that adds flexible cross-browser Flash objects to a page.

fb.flashObject can be used as a reliable and safe alternative to SWFObject, removing the need to have both scripts on the same page. It supports alternate content, Flash version checking, success and failure callbacks and provisioning of all Flash parameters.

A simple example:

fb.flashObject( { source: 'somePath.swf?wmode=transparent', $: 'someNodeId', width: 400, height: 300 } );

fb.getFormValues ( source )

Returns an associative array of all the name:value pairs respresenting 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.getLayout ( node, local )

Use getLayout to get the position and dimensions of any node (or image area element) on a page.

getLayout accepts a DOM node or an element's id string and returns an associative array (aka javascript object) containing the values 'left', 'top', 'right', 'bottom', 'width' and 'height'.
Coordinates a screen-based, not document coordinates. To get document coordinates, add in the current page scroll values.
If the optional second parameter is true and the node is inside an iframe, the returned 'left', 'top', 'right' and 'bottom' coordinates will be relative to that iframe's window, otherwise the coordinates are relative to the top page's viewport.

As of version 7.1, the returned object contains 3 sub-objects named 'margin', 'border', & 'padding' which contain named values of 'top', 'right', 'bottom', & 'left' giving the metrics for each of those element components.

The getLayout function differs from the native getBoundingClientRect in the following ways:

fb.getScroll ( win )

fb.getScroll returns the current amount by which the document is currently scrolled. The return value is an associative array containing the two named values 'left' and 'top'. Pass a reference to an iframe's window as the optional 'win' parameter to retrieve an iframe's current scroll state.
Example usage:

var scroll = fb.getScroll( ); alert( 'horizontal scroll is ' + scroll.left + ' pixels' ); alert( 'vertical scroll is ' + scroll.top + ' pixels' );

fb.getStyle ( node, property, numeric )

Returns the cascaded or computed (currently active) style for a given element.

The 'property' parameter is any css property specified using either CSS or camelCase (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 a number. E.g., a style of '49px' will come back as the number 49.
Example: size = fb.getStyle( 'someId', 'font-size' )
Equivalent to: size = fb.getStyle( '#someId', 'fontSize' )

fb.getViewport ( )

fb.getViewport returns the current dimensions in pixels of the browser window. The return value is an associative array containing the two named values 'width' and 'height'.
Example usage:

var viewport = fb.getViewport( ); alert( 'browser window is ' + viewport.width + 'x' + viewport.height + 'px' );

fb.hasClass ( node, className )

Returns a boolean value reporting whether the referenced node has className assigned to its 'class' attribute. The node can be passed in as a direct DOM node reference, or as a node's id. The className parameter is a string of one className to be checked for.

fb.iePre ( ver )

The fb.iePre function is a reliable way to detect if the user's browser is Internet Explorer and if so, which version.
If run without the optional 'ver' parameter, it will return the IE version number, or 0 if it's not IE.
If a version number is passed in, fb.iePre will return a boolean value indicating whether or not the browser is an IE version less than the 'ver' value. For example, fb.iePre( 9 ) will report true if called from IE 6, 7 or 8, and false from any other browser.

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.parseJSON ( str )

fb.parseJSON is a simple wrapper for the browser's JSON.parse routine. The advantage of parseJSON is that it does not raise a system error if the JSON string is malformed, but rather simply returns 'undefined'. Note that Floatbox will, at load time, backfill JSON.parse for old IE browsers that don't have it natively.

fb.preload ( imagePath, callback )

Fetches one or more images into the browser's cache.

Pass fb.preload the source path for the image to preload as a string. Or, pass an array of source path strings for multiple images to be preloaded.
If the optional callback function is provided as the second parameter, that function will be invoked when the image (or images) preload completes.
The callback function can accept a single parameter that will be the unattached img element containing the preloaded image.
If the image fetch succeeds, a parameter of 'ok' is set to true in the returned image. If it fails the returned image is Floatbox's small '404 not found' image.
If imagePath is an array, callback is called after the last image loads and the return value is an array of img elements in the same order as the passed array of sources.

fb.printNode ( node, style )

Use printNode to display a print dialog that will extract and print only the contents of a particular element, rather than the printing the full current 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 the top-most floatbox will be printed.
Styles can be applied to the print node's content using the optional style value. 'style' can be a string of css definitions (like those in a <style> element), or can be the path to a css file that contains the css definitions to be applied.

fb.ready ( func )

fb.ready is commonly used in the intial scripts that are executed at page load time. It queues functions until both the document is ready and the Floatbox code is fully present and initialized (including any old IE backfills). If fb.ready is called after everything is ready, the passed in function will be executed right away, and not queued.

fb.require ( source, callback, refetch )

Use fb.executeJS to dynamically load and execute external javascript files. The files will be "lazy-loaded", meaning their network fetch will be done after DOMContentLoaded. Files can come from any domain, local or foreign. Cross-domain scripting restrictions are not in effect.

The source parameter is the URL, or an array of multiple URLs, for the javascript resources to be loaded. They will be fetched in the order provided, allowing the javascript files to rely on dependencies amongst them.

callback is a function that will be executed when the source has finished loading and executing. If an array of sources was provided, the callback will fire after they have all completed.

fb.require keeps track of what has already been fetched and subsequent requests to fetch the same file are ignored (but the callback is still run). Pass true in the refetch parameter to load and execute a javascript source regardless if it's already been done in a previous call.

floatbox.js is actually just a bootstrap loader file which uses fb.require internally to marshall the rest of the Floatbox resources. This keeps pages loading as quickly as possible. With the exposure of fb.require to the API, there is no need to use another redundant loader or to burden page loads with a bunch of scripts during the page's initial rendering.
It's a good mechanism for fetching JSONC/JSONP data, loading API services such as those from Google Code, fetching common javascript from Content Distribution Networks, and for your own project files.

A simple example taken from the floatboxjs.com site which dynamically and unobtrusively attaches Google's translation widget to a few pages...

<script> function init() { ... } fb.require( "//translate.google.com/translate_a/element.js?cb=init" ) </script>

fb.removeClass ( node[s], className[s] )

The companion function to fb.addClass, removeClass accepts the same argument types and values as fb.addClass, but of course removes classes rather than adding them.

fb.select ( selector, baseEl, nth )

Provides the ability to select multiple elements using CSS selector syntax and gather matching elements into an array.

selector is any CSS selector string that the browser understands natively.
E.g., '.myClass' for a simple class name match,
or 'a.floatbox, .floatbox a:not(.nofloatbox)' for something more complex (this one gets all 'floatbox' marked links on a page).
Search for documentation on querySelectorAll to understand what's doing the work inside the fb.select function.

The baseEl function filters the returned set of elements to include only child elements of baseEl.

The nth parameter can be used to return a single element from the array of selected elements. It's a zero-based index so an 'nth' value of 0 returns the first element, 1 the second, and -1 is taken as a request for the last element in the array, -2 second to last, etc.

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.setStyle ( node[s], arg1, arg2 )

Use fb.setStyle to apply one or more CSS styles to one or more elements in a single call.

node can be an element reference, the element's id, or a CSS selector, and can be an array of any of those to assign to multiple elements or selectors.
An example using a selector:

fb.setStyle( 'table.xyz tc', { padding: 7 } );

arg1 and arg2 are flexible. To set a single style, use strings of the property name and value. e.g.

fb.setStyle( document.body, 'height', '100%' )

Set multiple styles at once by using a javascript object in arg1. e.g.

fb.setStyle( '#nodeId', { // can use 'nodeId' too backgroundColor: '#89abcd', opacity: 0.7 } );

CSS property names must be provided in javascript camelCase style, and not contain hyphens such as some CSS selectors do. For example, use 'zIndex', not 'z-index'.
Remove an assigned style, and thereby reset it to its cascaded stylesheet value, by passing an empty string ("") as the value.

fb.smallScreen

fb.smallScreen is not a function; it's a boolean value, to be referenced and not called.
It's a fairly reliable (but not perfect) detector of device screens that are smaller than 8 inches.
Use fb.smallScreen in javascript code to provide branching logic based on screen size.

fb.stopEvent ( e, stopPropagation, preventDefault )

fb.stopEvent is a cross-browser way to manage the bubbling (propagation) and default action behaviours for an event.

Pass the event to be halted as the first manadatory parameter.
The optional 'stopPropagation' and 'preventDefault' parameters give control over these specific aspects of the event sequence. 'stopPropagation' defaults to false while 'preventDefault' has a default value of true. Without explictly requesting different handling, the event will propagate but the default action will not fire.

fb.typeOf ( thing )

The fb.typeOf function extends javascript's builtin 'typeof' operator by resolving and correcting ambiguous 'object' return values.

The return value will be one of 'number', 'string', 'boolean', 'object', 'array', 'function', 'date', 'regexp', 'NaN', 'undefined', 'null', 'window', 'document', 'node' or 'unknown'.
Note that IE (all versions) has major problems handling dynamically created and destroyed windows inside iframes. fb.typeOf will detect a tombstoned window in IE and return a value of 'null' for it.

fb.usingTouch

Similar to fb.smallScreen, fb.usingTouch is a boolean value, not a function.
It does not report whether the device is touch-capable, but rather whether the user is currently using the touch interface. The distinction is important given the increasing number of hybrid devices that support both mouse and touch input. If the user switches back and forth between mouse and touch, fb.usingTouch will keep current in reporting the most recent input style.

Back to Index