Home > Articles > Home & Office Computing > The Web/Virtual Worlds/Social Networking

This chapter is from the book

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

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.

InformIT Promotional Mailings & Special Offers

I would like to receive exclusive offers and hear about products from InformIT and its family of brands. I can unsubscribe at any time.

Overview


Pearson Education, Inc., 221 River Street, Hoboken, New Jersey 07030, (Pearson) presents this site to provide information about products and services that can be purchased through this site.

This privacy notice provides an overview of our commitment to privacy and describes how we collect, protect, use and share personal information collected through this site. Please note that other Pearson websites and online products and services have their own separate privacy policies.

Collection and Use of Information


To conduct business and deliver products and services, Pearson collects and uses personal information in several ways in connection with this site, including:

Questions and Inquiries

For inquiries and questions, we collect the inquiry or question, together with name, contact details (email address, phone number and mailing address) and any other additional information voluntarily submitted to us through a Contact Us form or an email. We use this information to address the inquiry and respond to the question.

Online Store

For orders and purchases placed through our online store on this site, we collect order details, name, institution name and address (if applicable), email address, phone number, shipping and billing addresses, credit/debit card information, shipping options and any instructions. We use this information to complete transactions, fulfill orders, communicate with individuals placing orders or visiting the online store, and for related purposes.

Surveys

Pearson may offer opportunities to provide feedback or participate in surveys, including surveys evaluating Pearson products, services or sites. Participation is voluntary. Pearson collects information requested in the survey questions and uses the information to evaluate, support, maintain and improve products, services or sites, develop new products and services, conduct educational research and for other purposes specified in the survey.

Contests and Drawings

Occasionally, we may sponsor a contest or drawing. Participation is optional. Pearson collects name, contact information and other information specified on the entry form for the contest or drawing to conduct the contest or drawing. Pearson may collect additional personal information from the winners of a contest or drawing in order to award the prize and for tax reporting purposes, as required by law.

Newsletters

If you have elected to receive email newsletters or promotional mailings and special offers but want to unsubscribe, simply email information@informit.com.

Service Announcements

On rare occasions it is necessary to send out a strictly service related announcement. For instance, if our service is temporarily suspended for maintenance we might send users an email. Generally, users may not opt-out of these communications, though they can deactivate their account information. However, these communications are not promotional in nature.

Customer Service

We communicate with users on a regular basis to provide requested services and in regard to issues relating to their account we reply via email or phone in accordance with the users' wishes when a user submits their information through our Contact Us form.

Other Collection and Use of Information


Application and System Logs

Pearson automatically collects log data to help ensure the delivery, availability and security of this site. Log data may include technical information about how a user or visitor connected to this site, such as browser type, type of computer/device, operating system, internet service provider and IP address. We use this information for support purposes and to monitor the health of the site, identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents and appropriately scale computing resources.

Web Analytics

Pearson may use third party web trend analytical services, including Google Analytics, to collect visitor information, such as IP addresses, browser types, referring pages, pages visited and time spent on a particular site. While these analytical services collect and report information on an anonymous basis, they may use cookies to gather web trend information. The information gathered may enable Pearson (but not the third party web trend services) to link information with application and system log data. Pearson uses this information for system administration and to identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents, appropriately scale computing resources and otherwise support and deliver this site and its services.

Cookies and Related Technologies

This site uses cookies and similar technologies to personalize content, measure traffic patterns, control security, track use and access of information on this site, and provide interest-based messages and advertising. Users can manage and block the use of cookies through their browser. Disabling or blocking certain cookies may limit the functionality of this site.

Do Not Track

This site currently does not respond to Do Not Track signals.

Security


Pearson uses appropriate physical, administrative and technical security measures to protect personal information from unauthorized access, use and disclosure.

Children


This site is not directed to children under the age of 13.

Marketing


Pearson may send or direct marketing communications to users, provided that

  • Pearson will not use personal information collected or processed as a K-12 school service provider for the purpose of directed or targeted advertising.
  • Such marketing is consistent with applicable law and Pearson's legal obligations.
  • Pearson will not knowingly direct or send marketing communications to an individual who has expressed a preference not to receive marketing.
  • Where required by applicable law, express or implied consent to marketing exists and has not been withdrawn.

Pearson may provide personal information to a third party service provider on a restricted basis to provide marketing solely on behalf of Pearson or an affiliate or customer for whom Pearson is a service provider. Marketing preferences may be changed at any time.

Correcting/Updating Personal Information


If a user's personally identifiable information changes (such as your postal address or email address), we provide a way to correct or update that user's personal data provided to us. This can be done on the Account page. If a user no longer desires our service and desires to delete his or her account, please contact us at customer-service@informit.com and we will process the deletion of a user's account.

Choice/Opt-out


Users can always make an informed choice as to whether they should proceed with certain services offered by InformIT. If you choose to remove yourself from our mailing list(s) simply visit the following page and uncheck any communication you no longer want to receive: www.informit.com/u.aspx.

Sale of Personal Information


Pearson does not rent or sell personal information in exchange for any payment of money.

While Pearson does not sell personal information, as defined in Nevada law, Nevada residents may email a request for no sale of their personal information to NevadaDesignatedRequest@pearson.com.

Supplemental Privacy Statement for California Residents


California residents should read our Supplemental privacy statement for California residents in conjunction with this Privacy Notice. The Supplemental privacy statement for California residents explains Pearson's commitment to comply with California law and applies to personal information of California residents collected in connection with this site and the Services.

Sharing and Disclosure


Pearson may disclose personal information, as follows:

  • As required by law.
  • With the consent of the individual (or their parent, if the individual is a minor)
  • In response to a subpoena, court order or legal process, to the extent permitted or required by law
  • To protect the security and safety of individuals, data, assets and systems, consistent with applicable law
  • In connection the sale, joint venture or other transfer of some or all of its company or assets, subject to the provisions of this Privacy Notice
  • To investigate or address actual or suspected fraud or other illegal activities
  • To exercise its legal rights, including enforcement of the Terms of Use for this site or another contract
  • To affiliated Pearson companies and other companies and organizations who perform work for Pearson and are obligated to protect the privacy of personal information consistent with this Privacy Notice
  • To a school, organization, company or government agency, where Pearson collects or processes the personal information in a school setting or on behalf of such organization, company or government agency.

Links


This web site contains links to other sites. Please be aware that we are not responsible for the privacy practices of such other sites. We encourage our users to be aware when they leave our site and to read the privacy statements of each and every web site that collects Personal Information. This privacy statement applies solely to information collected by this web site.

Requests and Contact


Please contact us about this Privacy Notice or if you have any requests or questions relating to the privacy of your personal information.

Changes to this Privacy Notice


We may revise this Privacy Notice through an updated posting. We will identify the effective date of the revision in the posting. Often, updates are made to provide greater clarity or to comply with changes in regulatory requirements. If the updates involve material changes to the collection, protection, use or disclosure of Personal Information, Pearson will provide notice of the change through a conspicuous notice on this site or other appropriate way. Continued use of the site after the effective date of a posted revision evidences acceptance. Please contact us if you have questions or concerns about the Privacy Notice or any objection to any revisions.

Last Update: November 17, 2020