Facebook Connect: Display login button only when not connected to site

Currently i’m testing the features of Facebook Connect and i ran into troubles:

  • how to display the login button only if a user has not connected
  • how to display the image only if a user has connected

My simplest solution was to add some custom css classes:

  • fb-connecting: when the status of facebook connect is not known. e.g. display a “connecting…” message
  • fb-not-connected: when user is not connected to facebook. e.g. show connect button
  • fb-connected: when user is connected to facebook. e.g. show user picture and name

View the demo page

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xmlns:fb="http://www.facebook.com/2008/fbml"> 
<head>
 
  <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js" type="text/javascript"></script>
  <script src="http://static.ak.connect.facebook.com/js/api_lib/v0.4/FeatureLoader.js.php/en_GB" type="text/javascript"></script>
 
  <script type="text/javascript">
  $(function() {
    FB_RequireFeatures(["XFBML"], function() {
      FB.Facebook.init("[[[INSERT APP ID HERE]]]", "/xd_receiver.htm");
      FB.Connect.ifUserConnected(function(){
        $('body').addClass('fb-is-connected').removeClass('fb-is-not-connected');
      }, function(){
        $('body').removeClass('fb-is-connected').addClass('fb-is-not-connected');
      });
    });
  });
  </script>
 
  <style>
  .fb-connected, .fb-not-connected {
    display: none;
  }
  .fb-is-connected .fb-connecting, .fb-is-not-connected .fb-connecting {
    display: none;
  }
  .fb-is-connected .fb-connected {
    display: block;
  }
  .fb-is-not-connected .fb-not-connected {
    display: block;
  }
  </style>
 
</head>
<body>
 
<!-- fb-connecting: display while facebook is connecting -->
<div class="fb-connecting">Connecting to Facebook</div>
 
<!-- fb-not-connected: display when user is not connected to facebook -->
<div class="fb-not-connected">
  <fb:login-button v="2" size="medium"></fb:login-button>
</div>
 
<!-- fb-connected #1: display when user is connected to facebook -->
<div class="fb-connected">
  <fb:profile-pic uid="loggedinuser" size="square" facebook-logo="true"></fb:profile-pic>
  <fb:name uid="loggedinuser" useyou="false" linked="true"></fb:name>
</div>
 
<!-- fb-connected #2: actually, you can add the class to the xfbml-tags and do not need a sourrounding div-tag -->
<fb:name class="fb-connected" uid="loggedinuser" useyou="false" linked="true"></fb:name>

Tags: , ,

Leave a Reply