How To Create a Cool Animated Menu with jQuery

In this tutorial we’ll be building a cool navigation list complete with a sliding hover effect. Learn how to build the concept in Photoshop, lay out the basic HTML elements, style everything up in CSS then tie it all together with a few lines of jQuery to create a semantic, accessible and degradable menu design.

The design we’ll be building features a cool label image that slides into place under each navigation item on hover. We’ll build the design to work without jQuery first of all to ensure it’s widely accessible to users without Javascript enabled, then enhance the effect with jQuery for the majority of users.

Create a new document and fill the background with a light beige. Add a subtle 1.5% noise texture by going to Filter > Noise > Add Noise.

Use a subtle grunge Photoshop brush to add a little extra texture to the top centre of the canvas. Adjust the opacity to tone down the distressed effect.

Draw and fill a rectangle to create the base of the label graphic. Press CMD+T to transform the shape, then drag a guide to highlight the centre point.

Use the Polygonal Lasso tool to draw a small triangle. Use this triangle to clip out the bottom edges. Flip the selection horizontally and align with the guide to ensure the clipping is symmetrical.

The demo file uses just three images: A textured background image, the red label graphic and a repeating noise texture.

Create the basic HTML structure

The basic menu system first needs to be laid out as a HTML skeleton. Begin the page with a Doctype, followed by page title and a link to the CSS stylesheet. Write out the menu itself as a good old Unordered List element, with each

  • item containing an anchor.

    Style up the design with CSS

    Next, the CSS brings the design to life. Begin the CSS file with a quick reset to remove any default browser styling, then set up the surrounding page design by adding the repeating noise background texture to the page body. Centre up the

      with margin: auto; and text-align: center; and clear the element using overflow: hidden;.
      Float each

    • item to the left to place each nav item side by side. The rest of the styling can then go directly onto the anchors. Each anchor needs to have the exact dimensions of the label graphic, taking into consideration any padding used to position the text into place. Replicate the font styling from Photoshop using the same bold Helvetica styling, and use the CSS3 text-shadow property to recreate the Photoshop Drop Shadow. Finally, add the label graphic as a background image and set the position to -149px so it is hidden off screen until the mouse hovers the nav item.
      Set up the styling for the :hover effects by moving the background back into position and alter the colour of the font and shadow to ensure they can still be seen when the background colour changes… More

  • By Prithu Banerjee Posted in JQuery

    Making a Custom Facebook Wall with jQuery Templates

    In this tutorial, we are going to create our own version of Facebook’s wall. We will be using Facebook’s Graph API with jQuery, and the template plugin. The jQuery.tmpl plugin will allow us to define templates within our page, and convert the posts we’ve obtained from the API into a real HTML page.

    You can use today’s example to display a feed of the latest posts on your FB page or profile on your website.

    Before we begin, lets say a few words about the Facebook API.

    Update on June 19th, 2011: Recently Facebook introduced some changes to their API that broke this script. They now require that you use an access token in order to fetch the page feed, used by this example. The last section of this tutorial explains how to obtain such an access token.

    The Graph API

    The Graph is Facebook’s solution to providing an interface to every object that exists in the site, along with its connections to other objects. Every page that you see on the site has a corresponding graph representation, be it a user, photo, group, status update or anything else. The API also supports JSONP requests, which makes it really easy to use with jQuery.

    Note: although the API gives you access to everything on Facebook, you will need an API key to read non-public content. As this tutorial does not use an API key, it will only work if your wall is publicly accessible.

    We will be using two API datapoints – one for selecting the latest posts, and the other for selecting the full name and avatar of the page. You can see sample responses below:

    http://graph.facebook.com/smashmag/posts/

    01 {
    02     "data": [{
    03         "id""45576747489_10150136051797490",
    04         "from": {
    05             "name""Smashing Magazine",
    06             "category""Website",
    07             "id""45576747489"
    08         },
    09         "message""Creating a sphere with 3D CSS",
    10         "picture""http://platform.ak.fbcdn..",
    11         "link""http://bit.ly/epqBBv",
    12         "name""Creating a sphere with 3D CSS \u2013 Paul Hayes",
    13         "caption""www.paulrhayes.com",
    14         "description""A professional slice of newly..",
    15         "icon""http://photos-d.ak.fbcdn.net/photos..",
    16         "actions": [{
    17             "name""Share",
    18             "link""http://www.facebook.com/share.."
    19         }],
    20         "type""link",
    21         "application": {
    22             "name""Sendible",
    23             "id""26065877776"
    24         },
    25         "created_time": 1301325483,
    26         "updated_time": 1301325483,
    27         "likes": {
    28             "data": [{
    29                 "name""Zome Lia",
    30                 "id""100000643422735"
    31             }],
    32             "count": 16
    33         }
    34     }]
    35 }

    The JSON response above contains information on every one of the posts published by Smashing Magazine. Some of the fields contain data about the creation/modification date, number of likes and comments, title and description, and a type. This request could return status updatesshared links, uploaded photos andvideos, and more.

    We also need to make an additional request so we can obtain the avatar, associated with the page (it is not contained in the post responses):

    http://graph.facebook.com/smashmag/

    01 {
    02     "id""45576747489",
    03     "name""Smashing Magazine",
    04     "picture""http://profile.ak.fbcdn.net/hp..",
    05     "link""http://www.facebook.com/smashmag",
    06     "category""Website",
    07     "likes": 42696,
    08     "website""http://www.smashingmagazine.com/",
    09     "username""smashmag",
    10     "company_overview""Founded in September 2006..",
    11     "mission""The offical Smashing Magazine pa..!",
    12     "products""Looking for a web design job? Che.."
    13 }

    The picture field above gives us what we need. It is a bit of a waste to request so much data, so in the plugin we are actually limiting the returned fields to only what we need.

    The Templates

    Now lets say a few words about the jQuery templates. As the Graph API returns valid JSON data, it is a great candidate to experiment with jQuery’s template plugin. This official plugin enables us to define HTML building blocks with an easy to use markup. This saves us from having to manually create HTML elements, concatenate strings and escape character sequences.

    The templates themselves may be inserted inline in a special script tag, or can be received via an AJAX call from a separate file. In this tutorial, I’ve chosen the first approach as it is simple and straightforward.

    Each template has the following form:

    1 <script id="someID" type="text/x-jquery-tmpl">
    2 <!-- HTML markup coupled with template tags -->
    3 </script>

    This is a script tag which, because of the type attribute, is not recognized by the browser, so it is not evaluated nor shown. What is more, its content is treated as character data and is not parsed, which is perfect for the task of holding our templates. We can then use jQuery’s tmpl() method and render it into actual HTML markup (more on that in a moment).

    Here is the first template, which creates the heading of the page:

    1 <script id="headingTpl" type="text/x-jquery-tmpl">
    2 <h1>${name}<span>on Facebook</span></h1>
    3 </script>

    The ${} template tag gets replaced with the value of the name property of the object, that is passed to the tmpl() method, which in our case is the name of the facebook page.

    For a complete list of template tags and methods, read through the jQuery Template documentation.

    The other template, which displays the individual posts is a bit more complex and employs some of the more advanced templating features:

    01 <script id="feedTpl" type="text/x-jquery-tmpl">
    02 <li>
    03     <img src="${from.picture}" />
    04
    05     <div>
    06         <h2><a href="http://www.facebook.com/profile.php?id=${from.id}"target="_blank">${from.name}</a></h2>
    07         <p>{{html message}}</p>
    08         {{if type == "link" }}
    09             <div>
    10                 {{if picture}}
    11                     <img src="${picture}" />
    12                 {{/if}}
    13                 <div>
    14                     <p><a href="${link}" target="_blank">${name}</a></p>
    15                     <p>${caption}</p>
    16                     <p>${description}</p>
    17                 </div>
    18             </div>
    19         {{/if}}
    20     </div>
    21
    22     <p>${created_time} ·
    23     {{if comments}}
    24         ${comments.count} Comment{{if comments.count>1}}s{{/if}}
    25     {{else}}
    26         0 Comments
    27     {{/if}} ·
    28     {{if likes}}
    29         ${likes.count} Like{{if likes.count>1}}s{{/if}}
    30     {{else}}
    31         0 Likes
    32     {{/if}}
    33     </p>
    34
    35 </li>
    36 </script>

    Inside the template tags we can have any JavaScript expressions, even method and function calls. This is especially helpful when building the {{if}} statements, as you can see from the code above, where we check the number of likes and comments.

    One feature of the ${} tag is that it escapes the textual value before inserting it into the template. However in some cases this is not what you need. For example the message variable holds HTML code that we want to display as is. This is why we use the {{html}} tag instead, which preserves the original format of the code.

    And here is the HTML document we end up with:

    01 <!DOCTYPE html>
    02 <html>
    03 <head>
    04 <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    05 <title>Making a Custom Facebook Wall with jQuery | Tutorialzine Demo</title>
    06 <link rel="stylesheet" type="text/css" href="css/styles.css" />
    07
    08 </head>
    09 <body>
    10
    11 <div id="page">
    12
    13     <div id="wall"></div>
    14
    15 </div>
    16
    17 <!-- jQuery templates. Not rendered by the browser. Notice the type attributes -->
    18
    19 <script id="headingTpl" type="text/x-jquery-tmpl">
    20 <h1>${name}<span>on Facebook</span></h1>
    21 </script>
    22
    23 <script id="feedTpl" type="text/x-jquery-tmpl">
    24 <li>
    25     <img src="${from.picture}" class="avatar" />
    26
    27     <div class="status">
    28         <h2><a href="http://www.facebook.com/profile.php?id=${from.id}"target="_blank">${from.name}</a></h2>
    29         <p class="message">{{html message}}</p>
    30         {{if type == "link" }}
    31             <div class="attachment">
    32                 {{if picture}}
    33                     <img class="picture" src="${picture}" />
    34                 {{/if}}
    35                 <div class="attachment-data">
    36                     <p class="name"><a href="${link}" target="_blank">${name}</a></p>
    37                     <p class="caption">${caption}</p>
    38                     <p class="description">${description}</p>
    39                 </div>
    40             </div>
    41         {{/if}}
    42     </div>
    43
    44     <p class="meta">${created_time} ·
    45     {{if comments}}
    46         ${comments.count} Comment{{if comments.count>1}}s{{/if}}
    47     {{else}}
    48         0 Comments
    49     {{/if}} ·
    50     {{if likes}}
    51         ${likes.count} Like{{if likes.count>1}}s{{/if}}
    52     {{else}}
    53         0 Likes
    54     {{/if}}
    55     </p>
    56
    57 </li>
    58 </script>
    59
    61 <script src="js/jquery.tmpl.min.js"></script>
    62 <script src="js/script.js"></script>
    63
    64 </body>
    65 </html>

    The #wall div is going to be dynamically populated with the Graph API data, after it has been rendered using our templates. You can see the templates themselves at the bottom of the file. Before the closing body tag, I have included the jQuery library, the jQuery.tmpl plugin, and our script.js file, which we will be discussing next.

    jQuery Code

    As we have all the pieces in place, we can finally get down to writing our facebook wall plugin.

    script.js

    001 // Creating our plugin.
    002
    003 (function($){
    004
    005     $.fn.facebookWall = function(options){
    006
    007         options = options || {};
    008
    009         if(!options.id){
    010             throw new Error('You need to provide an user/page id!');
    011         }
    012
    013         // Default options of the plugin:
    014
    015         options = $.extend({
    016             limit: 15   // You can also pass a custom limit as a parameter.
    017         },options);
    018
    019         // Putting together the Facebook Graph API URLs:
    020
    021         var graphUSER = 'http://graph.facebook.com/'+options.id+'/?fields=name,picture&callback=?',
    022             graphPOSTS = 'http://graph.facebook.com/'+options.id+'/posts/?callback=?&date_format=U&limit='+options.limit;
    023
    024         var wall = this;
    025
    026         $.when($.getJSON(graphUSER),$.getJSON(graphPOSTS)).done(function(user,posts){
    027
    028             // user[0] contains information about the user (name and picture);
    029             // posts[0].data is an array with wall posts;
    030
    031             var fb = {
    032                 user : user[0],
    033                 posts : []
    034             };
    035
    036             $.each(posts[0].data,function(){
    037
    038                 // We only show links and statuses from the posts feed:
    039                 if(this.type != 'link' && this.type!='status'){
    040                     return true;
    041                 }
    042
    043                 // Copying the user avatar to each post, so it is
    044                 // easier to generate the templates:
    045                 this.from.picture = fb.user.picture;
    046
    047                 // Converting the created_time (a UNIX timestamp) to
    048                 // a relative time offset (e.g. 5 minutes ago):
    049                 this.created_time = relativeTime(this.created_time*1000);
    050
    051                 // Converting URL strings to actual hyperlinks:
    052                 this.message = urlHyperlinks(this.message);
    053
    054                 fb.posts.push(this);
    055             });
    056
    057             // Rendering the templates:
    058             $('#headingTpl').tmpl(fb.user).appendTo(wall);
    059
    060             // Creating an unordered list for the posts:
    061             var ul = $('<ul>').appendTo(wall);
    062
    063             // Generating the feed template and appending:
    064             $('#feedTpl').tmpl(fb.posts).appendTo(ul);
    065         });
    066
    067         return this;
    068
    069     };
    070
    071     // Helper functions:
    072
    073     function urlHyperlinks(str){
    074         return str.replace(/\b((http|https):\/\/\S+)/g,'<a href="$1" target="_blank">$1</a>');
    075     }
    076
    077     function relativeTime(time){
    078
    079         // Adapted from James Herdman's http://bit.ly/e5Jnxe
    080
    081         var period = new Date(time);
    082         var delta = new Date() - period;
    083
    084         if (delta <= 10000) {    // Less than 10 seconds ago
    085             return 'Just now';
    086         }
    087
    088         var units = null;
    089
    090         var conversions = {
    091             millisecond: 1,     // ms -> ms
    092             second: 1000,       // ms -> sec
    093             minute: 60,         // sec -> min
    094             hour: 60,           // min -> hour
    095             day: 24,            // hour -> day
    096             month: 30,          // day -> month (roughly)
    097             year: 12            // month -> year
    098         };
    099
    100         for (var key in conversions) {
    101             if (delta < conversions[key]) {
    102                 break;
    103             }
    104             else {
    105                 units = key;
    106                 delta = delta / conversions[key];
    107             }
    108         }
    109
    110         // Pluralize if necessary:
    111
    112         delta = Math.floor(delta);
    113         if (delta !== 1) { units += 's'; }
    114         return [delta, units, "ago"].join(' ');
    115
    116     }
    117
    118 })(jQuery);

    We are using the $.getJSON functions to request information from the Graph API. But you may notice that we are not using it as we have in previous tutorials, namely by providing a callback function as its second parameter. This is because we want both calls to the Graph API to be run in the same time (speed all the way), which is not possible with a simple callback.

    As of jQuery 1.5, all AJAX methods return a deferred object, which basically allows us to group a number of AJAX calls in a $.when(). After both of the AJAX requests complete successfully, the done method is executed once.

    After this, we can simply render the templates:

    1 // Rendering the templates:
    2 $('#headingTpl').tmpl(fb.user).appendTo(wall);
    3
    4 // Creating an unordered list for the posts:
    5 var ul = $('<ul>').appendTo(wall);
    6
    7 // Generating the feed template and appending:
    8 $('#feedTpl').tmpl(fb.posts).appendTo(ul);

    The tmpl() method takes a JavaScript object or array, and renders the template once per each element. The templates are specified by their ids (the #headingTpl and #feedTpl script elements in our case).

    Finally we only have to call the plugin in document.ready with the ID of your page, and your access token (more on this in a moment):

    1 $(document).ready(function(){
    2
    3     // Calling our plugin with a page id:
    4     $('#wall').facebookWall({
    5         id:'smashmag',
    6         access_token:'19304297594165|ZGyz1d0clt2XO3AyrjHmrKORo'
    7     });
    8
    9 });
    By Prithu Banerjee Posted in JQuery

    Hello world!

    Welcome to WordPress.com. After you read this, you should delete and write your own post, with a new title above. Or hit Add New on the left (of the admin dashboard) to start a fresh post.

    Here are some suggestions for your first post.

    1. You can find new ideas for what to blog about by reading the Daily Post.
    2. Add PressThis to your browser. It creates a new blog post for you about any interesting  page you read on the web.
    3. Make some changes to this page, and then hit preview on the right. You can always preview any post or edit it before you share it to the world.
    By Prithu Banerjee Posted in JQuery