Automatically Re-size Height in a Facebook Page Tab App to Prevent Scrolling

Facebook Page Tab Apps allow you to show any web content in an app that displays on your Facebook page.  This could be anything from a contact form to a survey, or even a newsletter signup form.  The content is displayed on Facebook through an IFrame, but it resides on your server, allowing you to connect to any necessary databases or web services to create a rich user experience.

If you have created a Page Tab App, you know that they are restricted to a maximum of 810 pixels in width, but no maximum height is specified in Facebook’s documentation.  During testing, you may find that you have to scroll in both the Facebook window and in the IFrame to view all of your app’s content, resulting in very unfriendly behavior for the end user.

With a small snippet of JavaScript and HTML, you can automatically re-size your Page Tab App’s IFrame to the size of your content.  You just need to include Facebook’s JavaScript SDK and a call to your app’s canvas.

Here is the code:

<div id="fb-root"></div>
<script>
  window.fbAsyncInit = function() {
	FB.init({
	  appId      : '{PASTE_YOUR_APP_ID_HERE}',
	  status     : true,
	  xfbml      : true
	});
	FB.Canvas.setAutoGrow();
  };

  (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";
	 fjs.parentNode.insertBefore(js, fjs);
   }(document, 'script', 'facebook-jssdk'));
</script>

Just include this code on your page and Facebook will automatically re-size your app to the correct height so you no longer have to scroll inside the IFrame. The great thing about the setAutoGrow method is that it sets a timer to automatically re-size your app’s canvas at a 100ms interval, so it will update if you have loaded any dynamic content on your page. Nice and easy!

Code Wars: Training in Programming Arts

As developers we have to frequently consult outside resources for information on how to complete certain tasks.  Whether it’s a book or an online tutorial, a quick refresher is always helpful to get a push in the right direction.  The problem is that we will often look for these resources when we know specifically what we need to do, rather than using them to buff up our skills.

There are many sites out there that allow you to do programming challenges to work on your proficiency with a language.  Project Euler, TopCoder or the Daily Programmer subreddit come to mind.  My newest addiction of this type of site is Code Wars.

What is Code Wars?

I like to explain Code Wars as a combination of small programming challenges and Xbox style achievements.  You complete a series of code “katas“: short snippets or bug fixes that test basic understanding of programming language concepts.  For each kata that you complete, you work your way up to higher ranks and increasingly more difficult tasks.

Code Wars Dashboard

The user dashboard in Code Wars.

Code Wars tracks the type of the katas that you complete into different types, such as bug fixes, algorithms and reference.  You can also complete katas in either JavaScript, Coffee Script or Ruby.  Since Code Wars starts with the basics, it is perfect for supplementing your learning of a new language.

Test Your Might

Code Wars provides you with a very simple code editor with syntax highlighting.  It works surprisingly well in the browser, complete with handling of indentation and other features.  You are also provided with the ability to write unit tests against your solution to test any cases that will help you complete the kata.  Then you submit your solution.  There becomes nothing more addicting than getting that green check mark every time you complete a kata.

The best feature of Code Wars comes after you complete a kata.  Once you submit your solution and it is verified, you get to see the solutions that other developers submitted as well.  Sometimes you will see solutions that are more complicated than your own, but quite often you will see solutions that are mind blowing in their simplicity.  I typically spend just as much time reviewing other’s solutions as I do coming up with my own.

Future Wars

I have no doubt that in the future Code Wars will bring support for more languages.  I’m excited at the possibility of completing code katas with Python or PHP.  I can’t help but think that Code Wars would also be an amazing tool for teaching people how to use the UNIX command line.

The beauty of Code Wars is that its katas are populated by user submissions, so it will continue to grow with new content in the as time goes on.

Want to test your skills?  Sign up by completing the example kata at http://www.codewars.com!  Thanks for reading!  If you would like, you can view my Code Wars profile here!

How to Write a jQuery Plugin – Part 3: Usage

In the parts one and two of my series on how to write a jQuery plugin, we learned how to create a simple jQuery plugin with the proper structure. We allowed the user to provide values for their own set of options and we allowed them to use our plugin with multiple elements by using a single class. Now we have a simple version of our plugin in a JS file ready to be used. In this post I will demonstrate how to import our plugin file to an HTML page and apply it to some elements on the page.

Importing Plugin Script File

If you have used jQuery plugins before, then this process is nothing new for you. You need only two things to use a jQuery plugin on a page; links to jQuery and the plugin file. We do that by adding these script tags to the head section of our page:

<script type="text/javascript" src="http://code.jquery.com/jquery-1.10.1.min.js"></script>
<script type="text/javascript" src="jquery.highlight.js"></script>

The first line loads the minified version of jQuery from the content delivery network (CDN) hosted by jQuery. This allows jQuery to be imported by your page without hosting on your server, but requires an internet connection so it cannot work with offline apps. The second line imports the file of our jQuery plugin. The sample file is available for download below.

Usage

Let’s say we have now added some content to our page. We have a couple of blocks of content that we want to use our plugin on. To identify these elements, we have added a class of “highlight” to each one. We want our plugin to activate when the page has finished loading. We can use the following JavaScript:

$(function () {
     $('.highlight').highlight();
});

The dollar sign ($) function is a shortcut for the $(document).ready() function in jQuery. So once jQuery has finished loading, it calls our plugin using the highlight function. Remember in the previous parts in the series we used jQuery’s extend features to add our highlight function directly into jQuery. Our plugin already handles multiple elements, so it will apply the effect to every element on the page that has the class “highlight”.

But what about our user options? How do we use those? Our plugin has an option called “cssClass” that allows us to control the class that gets added to the element to define the highlight options. All that we need to do is create an object that defines that value and pass it into our highlight function. Here is an example:

$(function () {
     $('.highlight').highlight({ cssClass: 'highlight-red' });
});

Our plugin will take the option values specified here and merge them with the default values we have set. The only thing we need is to define the highlight classes in CSS.

.highlight-yellow { background-color: yellow; }
.highlight-red { background-color: red; }

I’d like to note that in effect what we have done here is just add a class for the highlight effect to the elements through the plugin. Normally, we would not do this through a plugin, we would just use CSS, but it is a good learning example. If we wanted to, we could provide additional features that could not be done through CSS alone.

That’s it! Thanks so much for reading this far. Any questions or thoughts? Feel free to leave a comment here or let me know on Twitter!

How to Write a jQuery Plugin – Part 2: Options and Collections

In part one of my series on creating a jQuery plugin, I showed an example on how to structure a new custom plugin.  In this post, I’ll show you how to provide options for developers using your plugin and how to allow your plugin to handle multiple elements in the DOM.

User Options

You will remember in part one that we added an options parameter to our plugin’s main function.  It looked like this:

$.fn.highlight = function (options) {

This parameter is an object that will contain values for all of the options that the user will specify.  There is nothing special about this object.  It can hold any kind of data that you need to use as a setting for your plugin.  The problem with using this object directly is that we don’t want to require the user to set any options at all, if we don’t need them to.  However, we also don’t want to have to check to see if each value exists to specify a default.

jQuery’s built in extend function simplifies this down to a small piece of code.  See the example below:

var settings = $.extend({
     cssClass: 'highlight-yellow'
}, options);

In this snippet we are creating a variable in our plugin to hold our user settings.  To do this, we pass two things into jQuery’s extend function.  The first is an object that contains all of the default values that we wish for our plugin to use if the user does not specify their own value.  The second parameter is, you guessed it, the options variable containing the user’s specified values.  jQuery extend takes those two objects and merges them together, replacing our default values with the values in the options variable, if they exist.

In this case, I’ve added a very simple setting that will control the class that gets added to the content to highlight it in a specific color.  I will demonstrate how to use that in the next section.

Handling Loops and Collections

You may not realize it, but any time you are using a jQuery selector you are being returned a collection of elements.  This is the case whether or not there is or an only be one matching element on the page or not.  Selecting an element by class?  You get a collection of the elements that match that class.  Selecting an element by ID?  You still get a collection, but it contains only a single element.

This is important to understand because you will need to code your plugin to handle a collection of elements, rather than just one.  You can do this easily using jQuery’s each function.

return this.each(function () {
     // Adds the highlighter class to the element
     // Note the use of our settings object.
     $(this).addClass(settings.cssClass)
});

Inside of the each function is where we write the code for the core functionality of our plugin.  In this case, we want to add a class to every element that has been selected by the user. This will be how we add the highlight to each block of content.

Notice the use of the settings variable.  That object will contain either the default value or the user specified option value.  No extra work is required.

At this point, if we combine all of our code into a single file, we have a very simplified, but working plugin.  In the final part of the series, I will show you how to create your plugin file and complete all of the necessary steps to use it in an HTML page.

Until then, thanks for reading!

How to Write a jQuery Plugin – Part 1: Structure

One of the most beloved features of jQuery is that it is easily extensible. It requires little overhead to get a basic plugin started and it allows you to build reusable components on top of the power of jQuery. jQuery is already in use on many sites around the web. Creating a plugin allows you or other developers to easily drop your code into a site and start using it quickly.

Over the following three weeks, I will show you how to structure a basic plugin, provide a base set of features and how to package up and use your plugin on a page. Let’s get started this week with the basics of plugin structure.

Basic Structure

(function ( $ ) {
	$.fn.highlight = function (options) {
          // Our plugin code goes here.
	};
}( jQuery ));

The code snippet above outlines the basic structure of a jQuery plugin.  This may look out of the ordinary to you if depending on how you have worked with JavaScript in the past.  Let’s break it down.

Attaching to jQuery

Our plugin begins on line 1 with some strange syntax for declaring a function inside of parentheses.  At the end of the function’s brackets we have the “jQuery” variable in parentheses.  What’s up with that?

This takes advantage of a behavior in JavaScript called Immediately Invoked Function Expressions.  (I won’t go into detail about all that can be done with IIFE, but you can find more information here.)  The purpose of this code is to make sure that your plugin will work side-by-side with other libraries.  There are many libraries that use the $ character to provide an alias or shortcut (jQuery and ASP.NET AJAX are just two of many).

The last line of our plugin immediately passes the jQuery function into our IIFE, allowing us to use the $ alias within the scope of our plugin whether it is in use by another library outside of the plugin or not.

Plugin Declaration

On line 2 of the code above, we declare the $.fn.highlight function.  This is the main entry point of our jQuery plugin.  The function declaration also includes a parameter called “options”, which we will deal with in later parts of the series.

By attaching our function to $.fn, this makes it available anywhere in your application that jQuery is in scope.  You will likely recognize the syntax below that we can now use to call our plugin.

$(function () {
	$('p').highlight();
});

On page load, this will call the highlight function in our plugin for every paragraph tag on the page.  Feel free to try it out.  To run the code properly, you will need to include the plugin code in a file and include jQuery in your HTML file as well.

At this point, we have no code in our main function, so nothing will execute when our plugin is called.  However, in later installments we will add our plugin functionality and work with user defined options.

Thanks for reading!  Feel free to leave a comment or share this post.  Please come back next week for part two!