Javascript inside a Facebook profile tab

Posted: March 25th, 2010 | Author: Pierre Olivier Martel | Filed under: Facebook, Javascript, Rails | View Comments

Developing a Facebook application that runs in a profile tab can be a real pain in the neck. As stated on the Facebook developer wiki, one of the many constrains developing a Facebook tab forbids the use of external javascript files. This means you have to inline your javascript in a script tag in order to be processed by the Facebook FBML parser.

This is a real problem if you have javascript files for your Facebook application and wish to keep your code DRY. Here is the solution I came up with using Ruby on Rails and Facebooker :

# ApplicationController.rb
helper_method :request_is_facebook_tab? # Make the facebooker method available in views and helpers

# Application.fbml.erb
<%= render :partial => 'facebook/fb_js' %>

# _fb_js.fbml.erb
<% if request_is_facebook_tab? %>
  <%= javascript_tag output_js_files_content("Utility.js", "FBjqRY.min.js", "application-fb.js") %>
<% else %>
  <%= javascript_include_tag "Utility.js", "FBjqRY.min.js", "application-fb.js" %>
<% end %>

# facebook_helper.rb
def output_js_files_content(*files)
    output = files.collect { |f| IO.read(File.join(RAILS_ROOT, 'public', 'javascripts', f)) }
    output.join("\n")
end

This code will detect wether or not the facebook application is running inside a profile tab. If so, instead of generating an external javascript tag, an helper method is called to dump all the content of javascript files inside a script tag.

This solution lets keep your javascript where it belongs (inside .js files) and keep your code DRY when dealing with profile tabs limitation.


Alternate background colors with jQuery

Posted: September 26th, 2008 | Author: Pierre Olivier Martel | Filed under: Javascript, jQuery | View Comments

I did a little javascript function with jQuery this morning to alternate DOM elements background colors . The function takes in parameters an array of jQuery elements and an array of hexadecimal colors and changes the background color of each element with the next color in the array.

// Alternates the background colors of the elements passed in parameters
// elems  - Array of jQuery DOM objects
// colors - Array of hexadecimal colors
function alternateBgColor(elems, colors) {
  elems.each( function(index){
    var colorIndex = index % colors.length;
    $(this).css('background-color', colors[colorIndex]);
  });
}


It’s only a three lines function but the cool thing about it is that you can alternate through as many colors as you need. I’m only using two for now but this could come useful at some point! I like how everything javascript just got easier with jQuery.