- Application Dashboards and Counters
- Navigating and Showcasing Your Application Using Tabs
- Dynamic Content and the Facebook JavaScript (FBJS) Library
- Summary
Dynamic Content and the Facebook JavaScript (FBJS) Library
The Facebook JavaScript (FBJS) library is a solution prepared by Facebook to enable developers to execute JavaScript within their applications. Because allowing developers to perform the full range of JavaScript commands could lead to malicious use, FBJS attempts to provide a happy medium for providing access to simple animations and to utilizing event listeners and implementing Facebook dialog boxes. As you may have seen if you have tried to use JavaScript within Facebook before, all your variable names and functions are prefixed with an application ID. If your application ID is 1234567890 and you have a function named foo(), it becomes a1234567890_foo(). In the code for the application tab in the previous section, it was not possible to simply refresh the tab using window.location.reload() because of this, although you could use document.setLocation(), which is provided in the FBJS library. Because application tabs are the only way of enabling a user to showcase your application, it is important to add features such as Mock AJAX and animations to improve the usability of your work and to distinguish yourself from others.
The FBML Test Console (http://developers.facebook.com/tools.php?fbml) is a great resource for testing out your FBJS before deploying to an application tab (see Figure 8.6). It can also be used to test out a Facebook Platform application or to trial Facebook API methods before production.
Figure 8.6 Screen shot of the FBML Test Console showing an example application tab.
You can set the Position drop-down menu to tab to ensure that the correct proportions are being shown onscreen. When previewing your application in the Test Console, you are presented with a preview of how your application tab will look, the contents of the HTML that Facebook will generate, and a simple list of errors (as well as the ability to view a profile from the perspective of another user by setting the Profile text field). The remainder of this section uses the FBML Test Console to experiment with the various features of the FBJS library.
Facebook Animation Library
Facebook provides an easy-to-use library for creating a richer user interface for your users via CSS both inside Facebook and outside through an animation library (http://developers.facebook.com/animation/). This library could therefore be used to create animations for other applications that are not Facebook driven but utilize basic animations such as creating shading effects that "tween" between background or text colors or hiding and showing page elements. These could be used to animate a particular element and can be achieved in the following ways by populating the onclick() parameter of any element:
-
Animation(this).to("background', "#000").go();
This function will transition the element's current background color to black (#000) and is "executed" by supplying the final .go() method. The use of this ensures that the animation is performed on the current element but any other DOM object could also be passed into this function for manipulating elements in other areas of a page.
-
Animation(this).to("background", "#f00").to("color", "#fff").go();
You can string multiple styles together, such as background and color, as shown in the example. Both transitions will run smoothly in parallel, which means that as the background is changing color, so will the color of the text.
-
Animation(this).to("background", "#fff").from("#000"). go();
To transition between two styles irrespective of the current style, you can use a .from() method. In this instance, this meant changing the background from white (#fff) to black (#000).
-
Animation(this).by("font-size", "1px").go();
The .by() method can be used to increment or decrement an attribute, such as font-size, width, height, or left or right positioning.
-
Animation(element).to("height", 0).to("opacity", 0). blind().hide().go();
By setting the height and opacity of a supplied element, you can automatically hide it from view. You should also set the element's overflow style to hidden, which will prevent images contained within the element from still being shown despite it having no size. The .blind() method is used to prevent automatic text wrapping from occurring while the element is being resized.
-
Animation(element).to("height", "auto").from(0). to("width", "auto").from(0).to("opacity", 1). from(0).blind().show().ease(Animation.ease.end).go();
Revealing elements that have a display style set to none works in a similar way to hiding them but requires both a .to() and .from() method as well as .show() in replace of .hide(). A final, .ease() method was added to the animation, which will mean the element will "ease" into being revealed. Other options are Animation.ease.begin and Animation.ease.both, which will start slow and end fast or start and end slow, respectively.
All the animations above will occur over a duration of 1,000 milliseconds (1 second), but you can add a .duration() method right before .go() should you want the animation to last a longer or shorter time. The code examples available for this chapter contain a few animations to demonstrate how they function on application tabs and how they could be implemented in your own applications. A final advanced feature of the Animation library is checkpoints. Checkpoints are useful if you want to build an animation that consists of two or more logical steps that are part of a single animation. Example could be first increasing a width and then increasing its height or increasing the size of an element and then changing its color. This can be demonstrated using a simple example:
<div id="test_1" style="display: none; border: 1px solid #ccc; padding: 5px"> <span>This is a test message which will first increase in width and then in height.</span> </div> <a href="#" onclick="Animation(document.getElementById('test_1')). to('height', 0).from(0).to('width', 'auto').from(0).show().blind(). checkpoint().to('height', 'auto').blind().go(); return false;">Click to Expand</a>.
It is also possible to "stagger" checkpoints so that an action can be executed midway through the first animation. To implement this feature, you can add an additional parameter to the .checkpoint() function, which must be a number that ranges from 0 to 1, where 0 will not render the animation at all and a value of 1 will render the animation straight after the first has finished. For example, in the code above, you could set the checkpoint to 0.5 to start growing the height of the element halfway through its width increase. This can also be accompanied by a .duration(500) function just before .go() to ensure that both animations finish at the same time. A trick to delay animations is to use the following:
Animation(element).duration(3000).checkpoint().to("width", "auto").go();
This code would pause for 3,000 milliseconds (3 seconds) and then adjust the width of the given element. A use case for this may be to present a message after a certain period of time to the user or to hide a message after a number of seconds has elapsed. The final advanced feature of checkpoints is to use callbacks within the .checkpoint() function for performing animations on other elements as well as the current element. This can be achieved by using .checkpoint(1, function() { Animation(...); }) and nesting your animation within the two parentheses. Remember that you can also save these animation chains as functions and thus greatly reduce the amount of code you are typing and make it more readable if you call functions such as expand(), contract() or growThenFadeToBlack().
Facebook Dialogs
Facebook uses dialog boxes to alert users of messages that they have deleted and to alert them about errors and many other scenarios. To make your application blend in with their environment, they provide a Dialog object that can be manipulated to show a pop-up message called Dialog.DIALOG_POP or a contextual message called Dialog.DIALOG_CONTEXTUAL, which displays an inline dialog box rather than a pop-up. Both types of dialog work in similar ways, except that the contextual dialog can be displayed close to where the user's cursor is pointing or around a certain element. A simple dialog box can be created by using the following code:
<p><a href="#" onclick="new Dialog(Dialog.DIALOG_POP).showMessage('Test Dialog Box', 'Hello, World!', 'Close'); return false;">Click to Test Dialog Box</a></p>
The dialog box shows a message which has the title Test Dialog Box, the content set to Hello, World!, and its only button set to Close. The .showMessage() function could be replaced by .showChoice(), which accepts an additional parameter for allowing a cancel option. A more thorough example of using dialogs is to evaluate which action the user has chosen and to update an element:
1 <p>Do you like social programming? <a href="#" onclick="confirm('Do you like social programming?', this)">Click to Answer</a></p> 2 <p id="response">Unknown Response</p> 3 <script type="text/javascript"> 4 <!-- 5 function confirm(text, context) { 6 var dialog = new Dialog(Dialog.DIALOG_CONTEXTUAL); 7 dialog.setContext(context).showChoice("Social Programming", text, "Yes", "No"); 8 dialog.onconfirm = function() { 9 document.getElementById("response").setTextValue("Yes, I do."); 10 }; 11 dialog.oncancel = function() { 12 document.getElementById("response").setTextValue("No, I don't."); 13 }; 14 return false; 15 } 16 //--> 17 </script>
In this example, the results of the dialog box lead to the response element being updated either on being confirmed (lines 8 to 10) or canceled (lines 11 to 13). You can also see how the .setContext() function was used to ensure the dialog appeared close to the Click to Answer text. The final example of dialogs makes use of the <fb:js-string> FBML element to show a rich select box to the user within a message and enables them to update a string of text based on the color that they select:
<p id="body_text">This is some standard text.</p> <p><a href="#" onclick="update_text_color()">Update Text Color</a></p> <fb:js-string var="color_picker"> <p><b>What is your favorite color?</b></p> <p> <select id="color_select"> <option value="black">Default</option> <option value="red">Red</option> <option value="green">Green</option> <option value="pink">Pink</option> </select> </p> </fb:js-string> <script type="text/javascript"> <!-- function update_text_color() { var dialog = new Dialog(Dialoh.DIALOG_POP).showChoice("Color Picker", color_picker, "Pick", "Cancel"); dialog.onconfirm = function() { var color_text = document.getElementById("color_select").getValue(); document.getElementById("body_text").setStyle({color: color_text}); }; return false; } //--> </script>
The main difference in this example is that instead of passing a string of text into the .showChoice() function, the var of the <fb:js-string> element is used. This method can prove particularly effective if you intend to create a rich form that the user has to fill out or if you intend to include multimedia in your dialog box. The only methods that have not been explored are .hide(), which can be used to hide a dialog box if it is already opened (such as if you intend to open multiple dialog boxes or ensure that they are all properly closed), and .setStyle(), which can add styling to the dialog box.
Handling Events with an Event Listener
You might sometimes want to detect whether users have clicked an element on your application tab or moved their mouse over a text field or image. In these instances, you can set up an event listener that sits in the background of your code waiting for actions to occur. Facebook provides its own facilities to "listen" for events and has thus extended the W3C addEventListener() method. Event listeners are broken into three components:
- A string related to the event type that is being listened for, which includes mouse events such click, mousedown, mouseup, mouseover, mousemove, mouseout, or keyboard events like keyup, keydown, or keypress. To detect a particular key press, you can use the keyCode property of an Event object to perform specific functions dependent on keys. You can also use the Event object to detect whether the ctrlKey, shiftKey, or metaKey were pressed.
- A callback function that handles the event and triggers whatever functionality you want to implement. This could be updating a text box, adding text to row tables, or performing search "typeahead" functions. Two important functions can be set within this function: stopPropagation(), for preventing the listener from being added to any parent elements; and preventDefault(), for stopping an element's "normal" behavior (such as preventing clicking a link from directing the user). In the case of a link, you must also set its onclick attribute to return false;.
- The final parameter must be set and relates to a useCapture behavior, which should be set to false. This will prevent events being triggered for descendants of the element that triggers that particular listener.
You can use event listeners in two ways depending on what types of actions you want to capture. The first type of listener is used to encompass multiple elements and handle their logic within the callback function. For example, suppose you have a catalog of images and you want to update a text box to describe the image based on what product the user has rolled his mouse cursor over. You can do so using the following code:
<p id="product_description">Roll your mouse over an image to update this description.</p> <div id="products"> <p id="image_1"><img src="..." ... /></p> <p id="image_2"><img src="..." ... /></p> </div> <script type="text/javascript"> <!-- function handler(event) { var product_description = document.getElementById("product_description"); if (event.type == "mouseout") { product_description.setTextValue("Roll your mouse over an image to update this description."); return true; } var product_id = event.target.getId(); var product_text = ""; switch(product) { case "image_1": product_text = "This is the first product."; break; case "image_2": product_text = "This is the second product."; break; default: product_text = "This is an unknown product."; } product_description.setTextValue(product_text); } document.getElementById("image_1").addEventListener("mouseover", handler); document.getElementById("image_1").addEventListener("mouseout", handler); document.getElementById("image_2").addEventListener("mouseover", handler); document.getElementById("image_2").addEventListener("mouseout", handler); //--> </script>
The code above would display two images and accompanying text and has two listeners, mouseover and mouseout, which will either update the product_description element with a product description or reset it to its default text. The event.target.getId() function ensures that the correct element is identified, and then the JavaScript logic is tailored to that identifier. Another way to add an event listener is to completely separate the code from your application tab content:
<div id="test" style="border: 1px solid #ccc; padding: 5px; height: 50px; width: 100px" onclick="return false"></div> <script type="text/javascript"> <!-- function random_number(low, high) { return Math.floor((Math.random() * (high - low)) + low); } function color(obj) { var red = random_number (0, 255); var blue = random_number(0, 255); var green = random_number(0, 255); var color = red + ", " + green + ", " + blue; obj.setStyle("color", "rgb(" + color + ")"); } function load() { var obj = document.getElementById("test"); obj.addEventListener("click", function(event){ color(obj); event.stopPropagation(); event.preventDefault(); return false; }, false); } load(); //--> </script>
The code above will display a box that is clickable and that will change to a random color generated by the color() function. The difference in this example is that a click event is being captured and so the preventDefault() function is called to prevent the usual action of clicking an object. Note that only this second event listener can be validated using the FBML Test Console and the previous example of the product catalog must be hosted on a live application tab. Event listeners are the final component of the FBJS library explored in this section and can be used in combination with the Animation library and Mock AJAX. You should now feel well enough equipped to create an interactive and dynamic application tab that will keep your users coming back and that will persuade their friends to add one of their own.