What You’ll Learn in This Hour:
How to implement Facebook Like and Follow buttons
Ways to implement Facebook comments in web pages
Adding Google Maps to web pages
Dynamically controlling the pan and zoom of Google Maps
Creating Google Map markers in JavaScript
Implementing a Custom Google search
Displaying Twitter elements on your web page
Allowing users to Tweet directly from your web page
Adding Flickr photo streams to web pages
The sole purpose of this hour is to expand your ideas of what is possible through third-party interactions on your web pages. There are a lot of great services out there that you can incorporate directly into your web pages without needing to implement them yourself.
This hour covers a few of the most common external services that get incorporated into web pages: Facebook, Twitter, Google Maps, Google Search, and Flickr. Using these external services will save you a lot of time and provide your users with a better overall experience.
The social aspect of the Internet has been one of the biggest shifts since its inception. No longer is there a simple one-on-one interaction between a user and an Internet website. With the advancements of Facebook, you now take your friends along for the ride by sharing your experiences with them.
The main pieces this section focuses on are using Facebook controls to provide users with the capability to “like” your website, post specific pieces of your website on their walls, and make comments that appear in timelines.
There is a lot more to the Facebook SDK and the plug-ins than what is covered in this book. You might look at some additional possibilities: https://developers.facebook.com/docs/plugins/.
The first step in adding Facebook elements is to add the Facebook API to the web page. Facebook gives you the code snippet to add to your web pages to the API library. To see this, go to the following address, scroll down, and click the Get Code button to see the pop-up shown in Figure 16.1: https://developers.facebook.com/docs/reference/plugins/like/
Tip
If you have a Facebook developer account and an application ID, you can add the appId
parameter to the library path, as shown next:
js.src = "//connect.facebook.net/en_US/all.js#xfbml=1&appId={YOUR_ID_HERE}";
If you add the appId
, you can use Facebook Insights to get statistical information about the Like button clicks. You can register as a Facebook developer at the following location: https://developers.facebook.com/.
The code Facebook generates is shown next and is intended to be placed in your web page right after the <body>
element:
<div id="fb-root"></div>
<script>(function(d, s, id) {
var js, fjs = d.getElementsByTagName(s)[0];
if (d.getElementById(id)) return;
js = d.createElement(s); js.id = id;
js.src = "//connect.facebook.net/en_US/all.js#xfbml=1";
fjs.parentNode.insertBefore(js, fjs);
}(document, 'script', 'facebook-jssdk'));</script>
You may prefer to work with JavaScript and jQuery code directly, so the following code is converted script that can be added in an external JS file. The converted script, shown next, does the same thing that Facebook’s script does. It adds the #fb-root
element and then loads the SDK from Facebook into the web page:
function addFBsdk() {
$("body").prepend('<div id="fb-root"></div>'),
if ($("#facebook-jssdk").length == 0){
var fbSDK = document.createElement("script"); fbSDK.id = 'facebook-jssdk';
fbSDK.src = "//connect.facebook.net/en_US/all.js#xfbml=1";
$("head").get(0).appendChild(fbSDK);
}
}
$(document).ready(function(){
addFBsdk();
});
After you have the Facebook SDK loading properly in your page, adding a Like button is a simple matter of adding a <div>
element with class="fb-like"
. The following code shows an example of adding a Facebook Like button:
<div class="fb-like" data-send="true" data-width="450" data-show-faces="true"> </div>
The simplest method to getting the <div>
code for the Facebook Like button is go to the following URL and scroll down to the Get Like Button Code section. Fill out the form to style the Like button, and then click Get Code. You can ignore the code to load the SDK because you’ve already got it in the previous section. https://developers.facebook.com/docs/reference/plugins/like/
Adding a Send button for users to send your content to their friends is also very simple. All you need to do is add a <div>
element with class="fb-send"
and a data-href
that specifies the URL to send. The following code shows an example of adding a Facebook Send button:
<div class="fb-send" data-href="http://dayleycreations.com"></div>
To get the code for the Facebook Send button, go to the following URL and scroll down to the Get Send Button Code section. Fill out the form to style the Send button and then click Get Code. You can ignore the code to load the SDK because you’ve already got it in the previous section. https://developers.facebook.com/docs/reference/plugins/send/
A Facebook comment field can be a very important part of your user’s social experience. Users can see others comments, add their own, and even post comments directly to their own Facebook page (see Figure 16.2).
Adding a Facebook comments field for users to comment on your content is also very simple. Add a <div>
element with class="fb-comments"
and a data-href
that specifies the URL of the content. You can also set the height and number of comments to show using the data-width
and data-num-posts
attributes. The following code shows an example of adding a Facebook comments field:
<div class="fb-comments" data-href="http://dayleycreations.com"
data-width="470" data-num-posts="2"></div>
To get the code for the Facebook comments field, go to the following URL and scroll down to the Get Send Button Code section. Fill out the form to style the Comments field and then click Get Code. You can ignore the code to load the SDK because you’ve already got it in the previous section. https://developers.facebook.com/docs/reference/plugins/comments/
An extremely important element of web pages can be a map that shows the location(s) of your business or resources. Google Maps makes it extremely easy to add maps that are interactive to your web pages.
To add Google Maps to your web pages, you will need to have an API access key. However, if you are following along with this book and using only the localhost webserver, a key is not required.
When implementing Google Maps on a nonlocal host domain, you need to go to the following location and follow the instructions to get the API key. The key is free as long as your usage remains low. https://developers.google.com/maps/documentation/javascript/tutorial
After you get a key, you will be able to use that key to load the Google Maps API using a <script>
block similar to the one shown next:
<script type="text/javascript"
src="https://maps.googleapis.com/maps/api/js?key={YOUR_API_KEY}&sensor={TRUE_OR_FALSE}">
</script>
The sensor option specifies if your application uses a GPS or other type of sensor to determine the user’s location.
After the Google Maps API is loaded, you can add a map to your web page by adding a google.maps.Map
object to <div>
element, as shown next:
HTML code:
<div id="mapCanvas"></div>
JavaScript/jQuery Code:
var mapOptions = {
center: new google.maps.LatLng(-34.397, 150.644),
zoom: 6,
mapTypeId: google.maps.MapTypeId.SATELLITE
};
var map = new google.maps.Map($("#mapCanvas").get(0), mapOptions);
The Map()
function accepts the HTML DOM element object that will contain the map as well as a mapOptions
object. Table 16.1 describes the settings in the mapOptions
object.
After the Map object is created, it is added to the <div>
element. You can then use the Map
object in JavaScript to directly control the behavior of the map. The Map
object also includes events that fire when actions occur based on user interaction.
Google Map
events are attached to Map objects using the following syntax:
google.maps.event.addListener(mapObject, event, function);
Google Map
coordinates are specified by a google.maps.LatLng(x,y)
object, where x
and y
define the latitude and longitude. For example:
var mapPosition = google.maps.LatLng(50.555, 1.3);
As an example, the following code attaches a center_changed
event handler that sets the innerHTML
of an element #coordinates
with the current map center coordinates:
var map = new google.maps.Map($("#mapCanvas").get(0),
{center:new google.maps.LatLng(51,2),zoom:3,apTypeId:google.maps.MapTypeId.HYBRID });
google.maps.event.addListener(map, "center_changed", function(){
$("#coordinates").html(map.getCenter().toString());
});
Table 16.2 lists several of the methods, properties, and events that are attached to the Map
object.
There is much more to the Google Maps API interface. You can find additional information at https://developers.google.com/maps/documentation/javascript/.
As websites become more and more complex, the need to provide users with a way to quickly find what they are looking for becomes more critical. A simple way to do this is to add a custom Google search engine to the web page.
The custom Google search engine leverages the Google search technology to search your local web page. Google provides some simple controls with a text input and Search button, and then it automatically overlays the search results on top of your web page.
To get started, you will need to do the following:
1. Create a Google account if you do not already have one. An account can be created at
https://accounts.google.com/NewAccount
2. Go to the Google Custom Search page at the following address and click on a new search engine:
http://www.google.com/cse/manage/all
3. In the Sites to Search field, specify the URL(s) of your website and then give your site a name and click Create.
4. After you have created the custom engine, you will get a code snippet back similar to the following. You can use this code snippet to add the search controls to your website. You can get the custom control at any time by clicking the Get Code link in the Google Custom Search page.
<script>
(function() {
var cx = '####;
var gcse = document.createElement('script'), gcse.type = 'text/javascript';
gcse.async = true;
gcse.src = (document.location.protocol == 'https:' ? 'https:' : 'http:') +
'//www.google.com/cse/cse.js?cx=' + cx;
var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(gcse, s);
})();
</script>
<gcse:search></gcse:search>
This code is then placed in the actual HTML page where you want the search to appear. The code is basic JavaScript that loads the custom search engine JavaScript into a <script>
element on the web page. The <gcse>
tag ends up being replaced with the necessary HTML to implement the Google Custom Search by the Google API JavaScript.
Because you might prefer to work with jQuery, I’ve broken down the JavaScript from Google into a basic jQuery function shown next. This gives you more control as to when and how the search elements are added to the page:
function addCustomSearchEngine(){
var cx = "####";
var src = 'http:///www.google.com/cse/cse.js?cx=' + cx;
var search = $("<script></script");
search.attr("src", src).attr("async",true);
$("head").prepend(search);
}
Note
There are other customized options for the Google custom search engine that you can configure at the Google Custom Search page. You might prefer to turn off the ads displayed in the search results by clicking the Business Settings link. You also might want to enable searching for the entire web with a preference to your website.
The basic search is usually good enough for most applications. There is a lot more that you can do with the Google custom search engine and controls. For more information, you can visit https://developers.google.com/custom-search/v1/overview.
An important part of web pages today is the social interaction available. Twitter is one of the most prolific social mechanisms because of the simplicity. It is almost expected today that if a users desires, they can tweet about experiences interacting directly with websites as they are using them.
Twitter provides some great controls that are extremely easy to implement with minimal understanding of JavaScript. Specifically, you can add Tweet and Follow buttons as well as timeline displays and tweet displays. This allows you to easily incorporate Twitter elements to keep your website up to date.
To add Twitter controls to your web page, you need to load the Twitter JavaScript API library. Twitter provides the following code snippet that is added to the beginning of the <body>
element of the web page:
<script>!function(d,s,id){
var js,fjs=d.getElementsByTagName(s)[0];
if(!d.getElementById(id)){
js=d.createElement(s);
js.id=id;
js.src="//platform.twitter.com/widgets.js";
fjs.parentNode.insertBefore(js,fjs);
}
}(document,"script","twitter-wjs");</script>
You might want to use the following jQuery version:
function addTwitter(){
if ( $("#twitter-wjs").length == 0 ) {
var twitter = $("<script></script");
twitter.attr("id", "twitter-wjs");
twitter.attr("src", "https://platform.twitter.com/widgets.js");
$("head").append(twitter);
}
}
You can learn more about the Twitter API as well as adding Twitter elements at the following location:
To add a Tweet button to a web page, you need to add an <a>
element with the class="twitter-share-button"
. The Twitter JavaScript library adds the necessary interactions behind the scenes. When users click the Tweet button, it prompts them to log in if they haven’t already, and then it displays a Tweet pop-up dialog that allows the user to send the tweet about your web page.
You can specify several additional attributes listed in Table 16.3.
The following shows an example of a basic Tweet button element:
<a href="https://twitter.com/share" class="twitter-share-button"
data-url="https://dev.twitter.com" data-via="bwdayley"
data-lang="en">Tweet</a>
To add a Follow button to a web page, you need to add an <a>
element with the class="twitter-follow-button"
. The Twitter JavaScript library adds the necessary interactions behind the scenes. When users click the Follow button, they are prompted to log in if they haven’t already, and then it adds the user’s Twitter account to the following list of the specified accounts in the href
.
You can specify several additional attributes listed in Table 16.4.
The following shows an example of a basic Follow button element:
<a href="https://twitter.com/bwdayley" class="twitter-follow-button"
data-show-count="false" data-lang="en">Follow @bwdayley</a>
Another useful feature of the Twitter JavaScript API is the capability to embed a specific tweet in your website. This allows users visiting the website to retweet the embedded tweet for those following them.
To embed the tweet, you need to get a <blockquote>
string directly from Twitter by clicking the Details link at the bottom of the tweet and then clicking the Embed This Tweet link, as shown in Figure 16.6.
The following shows a code snippet of the embedded tweet:
<blockquote class="twitter-tweet">
<p>New Update.
<a href="http://t.co/n9Pfzfsc"
title="http://dayleycreations.com">dayleycreations.com</a> via @
<a href="https://twitter.com/bwdayley">bwdayley</a>
</p>
— Brad Dayley (@bwdayley)
<a href="https://twitter.com/bwdayley/status/291618492191477761"
data-datetime="2013-01-16T18:50:41+00:00">January 16, 2013</a>
</blockquote>
<script async src="//platform.twitter.com/widgets.js" charset="utf-8"></script>
If you have already embedded the Twitter API in the web page, you can ignore the <script>
element. The <blockquote>
code element is added to the web page wherever you would like the embedded tweet to be rendered.
Another useful feature of the Twitter JavaScript API is the capability to embed a timeline in your website. A timeline, shown in Figure 16.7, is an interactive control that lists tweets and allows users to reply, retweet, and add favorites. This is a great feature for websites that need a good social presence because the user never needs to leave the web page.
To embed the timeline, you need to get an <a>
string directly from Twitter by creating a timeline widget at the following location. Click the Create New button and then click the user timeline tab to create the widget: https://twitter.com/settings/widgets
In the bottom of the timeline widget window, you will see a text box with text similar to the following:
<a class="twitter-timeline" href="https://twitter.com/bwdayley"
data-widget-id="291668761717653506">Tweets by @bwdayley</a>
<script>!function(d,s,id){
var js,fjs=d.getElementsByTagName(s)[0];
if(!d.getElementById(id)){js=d.createElement(s);
js.id=id;js.src="//platform.twitter.com/widgets.js";
fjs.parentNode.insertBefore(js,fjs);
}
}(document,"script","twitter-wjs");</script>
If you have already embedded the Twitter API in the web page, you can ignore the <script>
element. The <a>
code element is added to the web page wherever you would like the embedded tweet to be rendered.
One common external service that is integrated into web pages are Flickr photo streams. Flickr provides a nice interface that provides the photo stream information in an easily consumable JSON object via a JSONP request.
It is easy to implement a Flickr stream using the jQuery AJAX request $.getJSON()
to make the JSONP request. All you need to do is make the AJAX request to Flickr and specify the feed id
. The following shows a couple of examples of using the Flickr API: one to get a photos_public
feed and the other to get a groups_pool
feed.
$.getJSON(url, "http://api.flickr.com/services/feeds/photos_public.gne?
341168865@N08&lang=en-us&format=json&jsoncallback=?");
$.getJSON(url, "http://api.flickr.com/services/feeds/groups_pool.gne?
650323@N24&lang=en-us&format=json&jsoncallback=?");
To get the id
attribute for the Flickr API request, go to the following location and enter the URL of the stream, as shown in Figure 16.9:
The following shows an example of the JSON object returned by the Flickr request:
{
"title": "Uploads from Hubble Heritage",
"link": "http://www.flickr.com/photos/hubble-heritage/",
"description": "",
"modified": "2012-12-19T14:26:47Z",
"generator": "http://www.flickr.com/",
"items": [
{
"title": "Planetary Nebula NGC 5189",
"link": "http://www.flickr.com/photos/hubble-heritage/8286901075/",
"media": {"m":"http://farm9.staticflickr.com/8199/8286901075_d9f154b8dd_m.jpg"},
"date_taken": "2012-12-19T09:11:05-08:00",
"description": " <p>...</p>",
"published": "2012-12-19T14:26:47Z",
"author": "[email protected] (Hubble Heritage)",
"author_id": "34168865@N08",
"tags": "heritage v nebula mus hubble "
},
{
In this hour, you learned how to incorporate external services into your web pages. You got a chance to add Facebook Likes and Comments. You also got to play around with adding Google Maps and dynamically controlling them. Next, you implemented some of the Twitter elements to give your web pages a better social appeal. Finally, you implemented some code to apply Flickr feeds directly into your web page.
Q. What other external services should I look at?
A. If you are planning to implement any kind of e-commerce on your web pages, look into Checkout by Amazon. There are a lot of good tools there with a name that customers trust.
Q. You showed an example of converting the generated HTML tags from Google, Facebook, and Twitter into JavaScript and jQuery functions. Is it better to use the original scripts or convert them?
A. That is totally up to you. They make the scripts so that web developers with absolutely no JavaScript or jQuery experience can still implement them. They are a bit awkward that way, so you can revise them so you can include the code in your general site JavaScript files.
The workshop consists of a set of questions and answers designed to solidify your understanding of the material covered in this hour. Try to answer the questions before looking at the answers.
1. How do you define a <div>
element as a Facebook Like button?
2. How do you detect that the center position of a Google Map has changed?
3. How do you specify related Twitter accounts in a Tweet element?
4. What AJAX method should you use to get the Flickr photo feeds, and why?
5. How do you get the current center position of a Google Map object?
1. Set class="fb-like"
.
2. Add a center_changed
listener using google.maps.event.addListener()
.
3. Set the data-related
attribute of the element to the related account.
4. .getJSON()
because the Flickr feed is a JSONP request.
5. Use .getCenter()
.
1. Open up the code in Listing 16.2 and modify the Google Maps example. Add a <select>
element, and when the Mark button is clicked, use jQuery to add a new <option>
element to the <select>
. Use the .data()
method to attach the coordinates of the position of the mark to the <options>
jQuery object. Then, add a change event handler for the select that will set the center of the Google Maps to the position attached to the selected <option>
.
2. Go to Flickr and find a new photo stream. Then go to idgettr.com and find the ID of the photo stream. Add a new left nav
item to the example in Listing 16.5 that links to that photo stream. You will need to determine whether to use the photos_public
or groups_pool.gne
location type.
3. Go to the following URL and read through the page. Then use the web form to generate code to recommend some of the other examples in this chapter.
https://developers.facebook.com/docs/reference/plugins/recommendations/