Floatbox v4.18 - Programmer's API Reference
randomous.comIndex
- Variables and Properties
- fb
- fb.instances
- fb.lastChild
- fb.topBox
- fb.parent
- fb.fbContent
- fb.currentIndex
- Floatbox Functions
- fb.start ( source, options ) *
- fb.end ( arg )
- fb.activateElements ( node )
- fb.restack ( instance )
- fb.ownerInstance ( node )
- fb.resize ( width, height, instance )
- fb.reload ( source, instance )
- fb.goBack ( )
- fb.cycleStop ( )
- fb.cycleGo ( )
- fb.pause ( bool )
- fb.showNext ( )
- fb.showPrevious ( )
- fb.showItem ( index )
- Event Callbacks
- afterFBLoaded
- beforeBoxStart
- afterBoxStart
- beforeItemStart
- afterItemStart
- beforeItemEnd
- afterItemEnd
- beforeBoxEnd
- afterBoxEnd
- beforePrint
- afterPrint
- Library Functions
- fb$ ( id ) *
- fb.flashObject ( url, width, height, params, node, id, altContent ) *
- fb.addEvent ( node, action, func ) *
- fb.removeEvent ( node, action, func ) *
- fb.stopEvent ( e ) *
- fb.extend ( objTarget, objSource [, objSource2 ...] ) *
- fb.executeJS ( strURI, callback ) *
- fb.getFormValues ( source )
- fb.serialize ( source )
- fb.deserialize ( str )
- fb.preload ( src, callback ) *
- fb.printNode ( node, style )
- fb.getElementsByClassName ( className, node ) *
- fb.getStyle ( node, property, integerize ) *
- fb.getScroll ( )
- fb.getDisplayWidth ( )
- fb.getDisplayHeight ( )
- fb.getDisplaySize ( )
- fb.getLayout ( node )
- fb.getIframeDocument ( iframe )
- fb.getIframeWindow ( iframe )
- fb.nodeContains ( parent, child ) *
- fb.hasAttribute ( node, attribute ) *
- fb.getOuterHTML ( node ) *
- fb.setInnerHTML ( node, html ) *
- fb.translate ( source, destLang, callback, plainText ) *
- fb.ajax ( { source: strURI, updateNode: node, callback: function(xhr), postData: form|object|strParams, cache: boolean, headers: { name: value [, name: value] } } ) *
* 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.
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.
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.)
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.
- strURI is the path to the swf file.
- width and height are the dimensions of the flash object in pixels.
- params (optional) is either an associative array or a string of parameters to be assigned.
The default parameters are { wmode:'opaque', scale:'exactfit', play:'false', quality:'high' } or, equivalently, 'wmode:opaque scale:exactfit play:false quality:high'.
(Please see http://kb2.adobe.com/cps/127/tn_12701.html for a complete list of available flash parameters.) - node is an optional parameter that can be a DOM element (normally a div) or the string id of an element. If given, the flash object will be inserted inside the node. If node is not provided, the flash object is written in place at the location of the script call using document.write().
- An id can be assigned to the flash object using the optional id parameter. An id is used when interacting with the flash object using scripted controls.
- Alternate content can be provided for client agents that don't have the flash plugin installed and active. Provide altContent as a string of html.
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:
- correctly sets the 'this' keyword in the event handler function
- passes the fired event object as a parameter to the event handler function
- sets the event.target attribute to the element that fired the event
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.
- source: Can be any of a node, a node's id, a nodeList, plain text or html to be translated, an array of any of the preceding, or null. If null, the default source is the currently opened floatbox and the content and captions of that floatbox will be translated in place.
- destLang: The two (or five) character language code for the translation to appear in. If not given, it defaults to floatbox's current language which is the detected browser localization language if not explicitly set in floatbox options.
- callback: Callback function to fire on completion of the translation. The callback will receive a single parameter of the Google translation results object which looks like this: { "responseData" : { "translatedText" : the-translated-text, "detectedSourceLanguage"? : the-source-language }, "responseDetails" : null | string-on-error, "responseStatus" : 200 | error-code } To get the translated text in in a callback of 'func(result)', use 'result.responseData.translatedText'.
- plainText: The default source content type is html. To translate plain text, set the plainText parameter to true. This mainly affects the handling of whitespace and newlines.
Important Notes:
- The translation request is sent as an encoded querystring on an HTTP GET request and is subject to URI length limitations. In practice this means an approximate limit of about 1200 characters of source html. (You can send an array of node references to retrieve a series of less than 1200 character translations.)
- The translation request may fail for any number of reasons such as the URI is too long, the source language cannot be detected, too many requests are made in a short time period (e.g., a long array), or the Google service may change its interface, have a service disruption or cease operation altogether.
- The content of a cross-domain iframed floatbox cannot be translated from code on the base page; the translate call must come from the iframed document itself.
- Translation calls are always asynchronous and have no return value.
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.
-
The source parameter is mandatory (the others are optional).
This is the URI of the page you are fetching the ajax content from.
'url', 'uri' and 'href' are allowed aliases for the 'source' parameter's name.
Note that ajax calls cannot go across different domains and that the source parameter must reference a resource that's on the same domain as the current page. For this reason, it's best to use relative URIs in your ajax calls (leave out the "http://someDomain.com" part). -
If the updateNode parameter is present, the element referenced by that parameter will be updated with the request's response text from the server.
Use this to automatically populate a div on your page with content from your ajax call.
updateNode can be either a DOM element object or the id of an element.
If there are anchors in the fetched content that are marked up for floatbox behaviour (i.e., have class="floatbox" on them), or there is other floatbox content such as cyclers or tooltips, that content will be automatically activated by fb.activateElements after the update.
Any inline javascript in the incoming content will be reliably executed. -
The callback function, if present, will be executed when the ajax request has completed and the response is available.
The parameter passed to the callback function ('xhr' in the example above) is the XMLHttpRequest object and allows you to access the ajax response values such as xhr.status and xhr.responseText.
The callback can be a proper function or a string to be eval'd. If a string, the 'xhr' parameter and xhr.responseText are not available.
(The callback function is fired when readyState is 4.) -
If the postData parameter is present, a POST request will be made to the server.
If postData is not present (or is empty), a GET request will be made.
The postData parameter is versatile: it can accept a query string of encoded name=value pairs separated by ampersands, an associative array (JSON object), a form DOM node, a form's id, or a form's name.
If postData points to a form, the form values will be properly serialized and the resultant encoded query string will be sent with the POST request.
Similarly, a JSON object will be serialized to an encoded query string.
Note: If you are passing a string directly and any of the name or value components might contain interesting characters, those names and values should be encoded using encodeURIComponent before being concatenated. - The cache parameter enables browser and proxy caching of the returned content - default is false.
-
The headers parameter takes an object of name:value pairs of custom request headers that are to be used in the ajax call.
Headers for caching, posting ('Content-Type'), and 'X-Requested-With' are already provided by the ajax function.
An fb.ajax call with custom headers might look like this:
fb.ajax({ source:'xyz.php', headers:{ 'Content-Type':'text/xml;charset=utf-8', 'X-My-Header':'MyValue' } });
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>