jCarouselLite version 1.1 released !

It has been quite a while since I worked on updating the jCarouselLite project. Meanwhile, the community has shown its love by actively contributing features and defect fixes. It is always a pleasant experience to see such active participation by the community, but there is also a challenge.

Many of the mods were spread around different websites, GitHub forks, Stack Overflow answers and comments. Consequently, it was not easy for a new user to start using it. So, I thought I should give some order to this by collecting them all back into the original project and that is exactly what I have done here… and much more…

Heads up! The plugin still weighs only 2 KB.

Given below is a list of items that has changed, leading to the release of version 1.1. Visit the project page and change log for more details.

  • Added a Github project. Feel free to raise any new defects or feature requests here
  • Updated to support jquery 1.11.x version
  • Fixed a few defects
    • We were skipping items in a particular rare combination of circular:true mode and scroll/visible/start options. Fixed
    • We were jumping to the top of the page when the navigation buttons are disabled in circular:false mode. Fixed
    • We were unintentionally styling grand-children of the main UL and LI. Now it will style only the top level UL and LI. Fixed
    • In circular:false mode, in a particular combination of total/visible/scroll options, we were unable to navigate to the last few items. Fixed
    • In auto-scroll mode, the Interval was not getting reset when next/prev navigation button was clicked. Fixed
    • In circular:false mode, with start:0, the prev button was not getting disabled. Fixed
    • Fixed an issue with some minification libraries
  • Changes to the project site
    • Introduced a Styling page to help you understand the default styling and ways in which you can apply custom styling to your carousel
    • Revamped the Demo page to make it cleaner and more beautiful. It is easier to view-source now than it was before
    • Updated the styling in Demo page to reflect the custom styling in Styling page
  • Added default options globally. This way you can set the default options using $.fn.jCarouselLite.options once instead of passing them for every carousel you create
  • Removed the separate width() and height() functions and replaced with jQuery.outerWidth(boolean)

At present, I am working on a few new features to the plugin and a few more additions to the project site. It will make this plugin even more useful and flexible. You can expect a 1.2 release for these enhancements in the next couple of weeks. Thanks again everyone for showing extraordinary interest in this simple and light weight carousel.

jQuery UI: Calling widget methods directly

A typical jQuery plugin is just another function attached to the jQuery object. As a plugin developer you write a function, attach it to jQuery.fn (just an alias for its prototype) and your plugin method is magically available to all jQuery instances. As a plugin user, you normally execute the plugin by calling a method on the jQuery object. Something like

// jCarouselLite is the plugin in this case
$("#carousel").jCarouselLite(options); 

The above call returns the jQuery object on which the plugin was originally invoked. That way you can chain method calls and marvel at the beauty of our wide one-liner solution. But not for long!!!

What if you would like to control the behavior of the plugin after initialization? What if you want to stop() what the plugin is doing, maybe add() something to it or maybe even destroy() it? There was no easy answer to that question and every plugin developer was left to his own creativity to come out with a solution.

var $carousel = $("#carousel").jCarouselLite(options); 
$carousel.stop();  // You cannot do this
$carousel.run(); // Nope! You cannot do this either
$carousel.destroy(); // Nope! You get the idea...

While developing jQuery UI, the team there recognized this as a generic problem and came up with a generic solution. They called it the Widget Factory and popularized it as a way to develop Stateful plugins as opposed to traditional Stateless plugins. Take a look here to know more about how to develop jQuery plugins using the Widget Factory Pattern. All jQuery UI widgets are examples of plugins developed using the Widget Factory. Lets take one interaction with the jQuery UI

var $accordion = $(“#accordion”).accordion(options);
$accordion.accordion(“enable”); // Enable the accordion
$accordion.accordion(“activate”, 1); // Activate the second tab

As can be seen above, now you can interact with the Accordion after initialization by passing a method name as string. For instance, “enable” is a method that takes zero arguments and enables the accordion and “activate” is another method that takes one argument (an index) to be activated and opens up the accordion tab at that index.

It works, but wouldn’t it be cool if we don’t pass in method names as strings and would get to call the methods directly on $accordion – like $accordion.enable()?

It so happens that the $accordion is not an instance of the widget itself, but a jQuery object that wraps the DOM element representing the accordion. In most situations that is what you will need and so that is what is given to you.

The good news is that, the actual widget instance is stored with the corresponding DOM element using jQuery.data(). The plugin’s name is used as its key. Therefore, you can call $accordion.data(“accordion”) and enjoy direct access to all its plugin methods without retorting to indirect, string based approach anymore.

var $accordion = $(“#accordion”).accordion(options).data(“accordion”);
$accordion.enable(); // Enable the accordion
$accordion.activate(1); // Activate the second tab

Now you can have your cake and eat it too…

JQuery: Wait for multiple animations to Complete – Take 2

In an earlier blog post, I stated the need for a technique that helps determine when multiple animations have completed running, so that we can execute some code at that point. I also examined a technique using a combination of setInterval() based polling and checking for the :animated pseudo-class to achieve the result.

With the release of version 1.5, jQuery introduced the concept of Deferred Objects. It’s a pretty useful beast. You can find the full explanation here. In jQuery 1.5, the $.ajax() was enhanced to return a Deferred Object, but $.animate() was cheated without being given that honor. That was corrected with the release of jQuery 1.6 and now you receive a Deferred Object as a return value for $.animate() and its higher-level cousins.

Using the returned Deferred Object, and another useful utility function named $.when() we don’t have to stoop down to using poll-based techniques to wait for multiple animations to complete. Take a look at the code below and you will agree that it can be done much more cleanly now.

var animatingFoo = $("#foo").slideUp(1000);
var animatingBar = $("#bar").slideDown(3000);

$.when(animatingFoo, animatingBar).done(function() {
  // Do something useful
});

Here, both the slideUp() and slideDown() methods return a Deferred Object. Although we can attach the done() event-handler to the animatingFoo and animatingBar separately (which will get fired separately when the individual animations are complete), that is not what we are after. We want to execute our code after both the animations are complete. For this purpose we call in the help of a utility function $.when().

$.when() aggregates multiple deferred objects and returns a single deferred object. Now, if we attach our done() event-handler to the aggregated deferred object, it will get fired only after both the animations are complete, which solves our requirement.

GWT – Pros and Cons

I love JavaScript. With the advent of jQuery and Mootools, my love for JavaScript has only increased plenty-fold. Given a choice I would use either of the aforementioned frameworks for any web application I develop. But being in the service industry, time and again I have to succumb to the client’s pressure and work in their choice of technology – whether or not it is the right one (The one who pays the piper calls the tune. Isn’t it?). One such client exposed me to the world of GWT.

I have given GWT a shot couple of years back on the day it was released. I didn’t like it that much then, so I dismissed it and never returned back. But, over the past six months working on this project I have a slightly different impression on this framework. I still cannot say that GWT is the next big thing since sliced bread, but at least it is not as bad as I thought it was. I have just documented my observations, both good and bad during the course of this project and thought some fellow developer might find it useful while evaluating GWT.

Pros:

  1. If you are a Java veteran with experience in Swing or AWT, then choosing GWT should be a no-brainer. The learning curve is the least with this background.
  2. Even if you are not experienced in Java GUI development, the experience in working on server-side Java for years will come in handy while developing GWT apps
  3. You can create highly responsive web applications with heavy lifting on the client-side and reduced chattiness with the server-side
  4. Although there are numerous JavaScript libraries out in the wild and most of them are worth their salt, many conventional developers don’t understand its true power. Remember, a powerful language like JavaScript is a double-edged sword. If you don’t know how to use it, even you won’t be able to clean the mess you create
  5. You can migrate from a typical web application to a GWT application iteratively. It is not an all or nothing proposition. You can use a clever trick called JSNI to interact with loads of JavaScript functions you already possess. But it is always better to move them to GWT sooner rather than later
  6. The IDE support for GWT cannot be better. Java IDEs have matured over the past decade to be one of the best in the world and GWT can take direct advantage of it
  7. The integrated debugging beauty is something you can kill for. The excellent debugging support offered by the mature Java IDEs is one feature that could sway anybody’s decision in favor of GWT
  8. The built-in IDE support to refactor Java code can directly be put to good use to maintain a simple design at all times. Doing this in JavaScript is not for the faint at heart
  9. The IDE syntax highlighting, error checking, code completion shortcuts etc are overwhelming – to say the least
  10. GWT is being actively developed by Google. We know that the project is not going to die off anytime soon. Until now their commitment towards the project says a lot about its future in the industry.
  11. The community behind the project is also a big PLUS. Discussions take place daily in Stack overflow, discussion forums, wikis and personal blogs. A simple search with the right keyword could point you in the right direction
  12. GWT is a well thought-out API; not something that was put together in a hurry. This helps you as a developer to quickly comprehend the abstractions and makes it really intuitive to use
  13. You can use GWT’s built-in protocol to transfer data between the client and the server without any additional knowledge of how the data is packaged and sent. If you prefer more control, you can always use XML, JSON or another proprietary format of your choice. Even in that case, while using JSON, you don’t have to use an non-intuitive java JSON library. You can use JSNI to ‘eval’ the JSON using straight javascript. Cool huh!
  14. You have the advantage of being able to use standard Java static code analyzers like FindBugs, CheckStyle, Detangler, PMD etc to monitor code and design quality. This is very important when you are working in a big team with varying experience.
  15. You can use JUnit or Test NG for unit testing and JMock or another mock library for mocking dependencies. Following TDD is straight-forward if you already practice it. Although there are JavaScript based unit testing frameworks like jsunit and qunit, come on tell me how many people already know that or are itching to use that.
  16. The GWT compiler generates cross-browser JavaScript code. Today, any marketing person who says this will probably be beaten. It has now become a basic necessity, not a luxury
  17. The GWT compiler optimizes the generated code, removes dead code and even obfuscates the JavaScript for you all in one shot
  18. Although the compilation process takes hell a lot of time, you don’t have to go through that during development. There is a special hosted mode that uses a browser plug-in and direct java byte-code to produce output. That is one of the main reasons you are able to use a Java debugger to debug client side code.
  19. Rich third-party controls are available through quite a few projects like Smart GWT, Ext GWT etc. They are well designed, easy to use and theme-able. So, if you have a requirement where existing controls don’t just cut it, you should be looking into one of these projects. There is a really fat chance that one of those components will work out. Even if that doesn’t work out, you can always roll out your own.
  20. GWT emphasizes the concept of a stateful client and a stateless server. This results in extremely less load on the server where many users have to co-exist and high load on the client where only one user is working
  21. I18N and L10N are pretty straight-forward with GWT. In fact locale based compilation is taken care by the GWT compiler itself. The same cannot be said about regular client-only frameworks
  22. GWT comes built-in with browser back button support even while using AJAX. If you are an AJAX developer, I can almost feel your relief. This is priceless.

Cons:

  1. GWT is a fast developing project. So, there are a lot of versions floating around. Many functions, interfaces and events get deprecated and keeping up with their pace is not too much fun when you have other work to do
  2. There were quite a few GWT books during the beginning. Not so much these days. For example, I haven’t found many books on the 2.0 version of GWT. This leaves us only with Google’s documentation. I agree that the documentation is good and all, but nothing can beat a well written book
  3. GWT is not fun to work with. After all it is Java and Java is not a fun language to work with. If you add the fact that entire layouts and custom controls should be created in java, you can easily make a grown programmer cry. With the introduction of UI binder starting version 2.0, that problem is kind of solved, but now you have a new syntax to learn.
  4. The Java to JavaScript compilation is fairly slow, which is a significant con if you choose GWT.
  5. I personally prefer defining structure in HTML and styling it using CSS. The concepts used in HTML are clean and straight-forward and I have years of experience doing just that. But in GWT, I am kind of forced to use proprietary methods to do the same. That combined with the fact that GWT doesn’t solve the styling and alignment incompatibilies for me compounds the problem. So, writing layout code in GWT is something I despice. But with UI Binder and HTMLLayout from version 2.0 onwards, I feel I am back in my own territory
  6. It requires some serious commitment levels to get into GWT, coz, after that, a change in client side technology could require a complete rewrite of your app, as it is a radically different approach than other client side frameworks
  7. There is not a defined way to approach an application development using GWT. Should we use only module per app or one module per page or somewhere in between. These design patterns are slowly evolving only now. So, typically people tend to develop all in one module until the module size goes beyond being acceptable and then they refactor it into multiple modules. But if it is too late, then refactoring could not be that easy either
  8. Mixing presentation and code doesn’t sound right although typical desktop GUI applications does just that. But these days, even desktop application frameworks like Flex and Silverlight have taken an XML based declarative approach to separate presentation from logic. I think GWT 1.x version had this disadvantage. With the introduction of UI Binder starting from version 2.0, I think this disadvantage can be written off although it is yet another painful XML language to learn
  9. You would often be punching in 3X to 5X more code than you would with other client libraries – like jQuery – to get simple things done
  10. You should also remember that with GWT, the abstraction away from HTML isn’t complete. You’ll still need to understand the DOM structure your app is generating in order to style it, and GWT can make it harder to see this structure in the code.
  11. GWT is an advantage only for Java developers. Developers with .NET or PHP background won’t gain anything here
  12. If you have tasted the power of JavaScript and know how to properly utilize it to your advantage, then you will feel crippled with an unexpressive language like Java

I am sure many of you will have differences of opinion. Difference is good. So, if you think otherwise, feel free to leave a comment. We’ll discuss…

GWT – Not enough methods, expecting 3 saw 2

In my current project we use GWT extensively. I also develop prototypes and POCs for clients using GWT when I am in presales mode. During one such prototype, when I was using GWT RPC to perform an AJAX call from the client to the server, I hit a road block. GWT was throwing me an error I couldn’t comprehend.

java.lang.AssertionError: Not enough methods, expecting 3 saw 2

After a bit of fiddling and googling around, I realized that this was happening because I recently upgraded from version 2.0.3 to version 2.2. I guess the protocol GWT uses to serialize the data to be transported between the client and the server has changed between these two versions. Fair enough. But I don’t understand why I received that error although I created this project after upgrading to version 2.2.

Anyways, I found out that for some odd reason the gwt-servlet.jar that was stuck to my lib folder was the older 2.0.3 version. When I replaced it with the 2.2 version of the jar file the problem got fixed. FYI, the 2.0.3 version of the jar is around 1.5 MB whereas the 2.2 version of the jar is around 4.5 MB.

Meanwhile, I am working on a list of pros and cons for using GWT. Will be posting that soon…

Is it an AJAX Request or a Normal Request?

In modern web application development, many a times you would want to know if the incoming HTTP Request is an AJAX request or just a Normal request. Have you come across this requirement? I have, and the solution that I found turned out to be pretty straight-forward and I will be sharing it with you here.

Whenever an AJAX request is sent to the server, a special header named X-Requested-With with a value of XMLHttpRequest is attached to the request. So, a simple check to see whether the X-Requested-With header has a value of XMLHttpRequest solves the challenge. An example will give you more clarity. Take a look at the examples of isAjax() methods in two famous server-side programming languages – Java and PHP.

Java:

public static boolean isAjax(request) {
   return "XMLHttpRequest"
             .equals(request.getHeader("X-Requested-With"));
}

PHP:

function isAjax() {
   return (isset($_SERVER['HTTP_X_REQUESTED_WITH']) 
              && 
            ($_SERVER['HTTP_X_REQUESTED_WITH'] == 'XMLHttpRequest'));
}

From the code above, it should be clear that if the method returns true, then you received an AJAX request. If the method returns false, you received a Normal HTTP Request.

Now you know how to find out if it is an AJAX request or not. But how is it useful? What do you do with it?

Have you heard of the term Unobtrusive javascript. Come on, It is a buzzword these days. There is a lot to writing Unobtrusive javascript code, but one of its features – Progressive Enhancement – stands out from the rest. Again, let me explain this with an example.

Let us assume that you have designed a beautiful looking web page with tabbed navigation. Being a hard-core AJAX fan and an efficiency aficionado you don’t like to bring back a full page with the headers and the footers and the sidebars when your user clicks on a Tab. Instead you would love to bring back only the content area for the tab via AJAX and innerHTML it into its respective place. Correct? The good programmer inside you has also told that you should not hard-code the URL for the AJAX call in your javascript. Instead, your tab should be designed as an anchor whose href attribute points to the URL for the content. So far so good? Now, when the user clicks on the Tab, you collect the URL from its href attribute and fire an AJAX call to the server. The server obediently accepts the request and sends back the content just for the active tab.

<ul>
   <li><a href="/tab1.page" rel="#tab1">Tab 1</a></li>
   <li><a href="/tab2.page" rel="#tab2">Tab 2</a></li>
   <li><a href="/tab3.page" rel="#tab3">Tab 3</a></li>
</ul>

<div>
   <div id="tab1">Content for Tab1</div>
   <div id="tab2"> Content for Tab2 </div>
   <div id="tab3"> Content for Tab3 </div>
</div>

You would like to believe that all is well and good… Unfortuntately this is where the challenge of Progressive Enhancement begins. How do you plan to support browsers with JavaScript disabled. Yes, there are quite a few people who still do that for the fear of script related worms. How do you plan to support automated bots? Don’t you want the Google bots and the Yahoo bots to index all your pages with full content? Do you know what these users will see? They will see a half-baked page with just the active tab’s content and no styles – not even the header, footer or the sidebar. I am sure you don’t want this to happen. That is when the isAjax() method comes useful.

Whatever you did on the client side – HTML, CSS and javascript – is great and perfect. You separated the behavior from style and markup. So, you don’t have to touch it. You just need to do a small bit of work on the server-side.

In our case, when JavaScript is disabled, the browser will take over and execute its default behaviour of firing a Normal request to the URL specified in the href attribute. When JavaScript is enabled, JavaScript will take over and will fire an AJAX request to the same URL. In both cases the same server-side resource (like in Java or PHP) will receive the request. Now that you have decided to support Progressive Enhancement, you will have to check if the incoming request is an AJAX request or a Normal request using the isAjax() method shown earlier. In case of an AJAX request, you will send back only the content area of the tab thereby providing an efficient version of your application to JavaScript enabled users. In case of a Normal request, you will send back an entire page including the tab’s content, thereby providing a less efficient yet fully functional version of your application to JavaScript disabled users.

// Pseudo Code
if(isAjax(request) {
   return "Content area for the tab";
} else {
   return "Full page including tab content";
}

Now you can feel proud that you are not one of those who just talk about Unobtrusive JavaScript but you are one of those who have implemented it. I sincerely hope this article was useful. Feel free to drop in a comment with suggestions and/or feedback.

Update 1:

Based on the input provided by a buddy called Sabob from dzone, X-Requested-With is set only by AJAX libraries like jQuery, Mootools, Prototype etc. If you are coding AJAX by hand, then you will have to explicitly set this header while sending a request. More importantly you should somehow abstract it using good OO principles so that you don’t have to explicitly code this line every time you send an AJAX request.

Ctrl + Key Combination – Simple Jquery Plugin

In a recent web application I was working on, I had a need for the “Ctrl + S” hotkey to save an entry to the database. Being a an avid jquery fan, I immediately searched the plugin repository for any plugin that fits the bill. I was not very surprised to find a very comprehensive jshotkeys plugin. It was feature rich and addressed all the requirements for hotkeys in a jquery powered application and obviously my requirement was fulfilled as well.

But the basic issue (and advantage too) with any plugin is that it is written for a wide range of audience. So, although my requirement was only for a “Ctrl + key” combination, I had to part with my bandwidth for all other features this plugin offered. Like my famous jCarouselLite plugin, I like my javascript code kept to the minimum. So, I decided and wrote a short yet sweet plugin that would solve only the problem I have at hand. Unsurprisingly, the plugin code turned out to be only 195 bytes (minified). Given below is the code for the same…

$.ctrl = function(key, callback, args) {
    var isCtrl = false;
    $(document).keydown(function(e) {
        if(!args) args=[]; // IE barks when args is null
        
        if(e.ctrlKey) isCtrl = true;
        if(e.keyCode == key.charCodeAt(0) && isCtrl) {
            callback.apply(this, args);
            return false;
        }
    }).keyup(function(e) {
        if(e.ctrlKey) isCtrl = false;
    });        
};

This is how it works:

1. You want to execute a function when the user presses a “Ctrl + key” combination.
2. You as a developer should call the plugin method and pass in 3 parameters.
3. 1st Param: The “key” user should press while he is pressing Ctrl.
4. 2nd Param: The callback function to be executed when the user presses “Ctrl + key”.
5. 3rd Param: An optional array of arguments, that will be passed to the callback function.

In the code given below, when the user presses the “Ctrl + S” key combination, the anonymous callback function passed in as the second parameter is called.

$.ctrl('S', function() {
    alert("Saved");
});

Here, when the user presses the “Ctrl + S” key combination, the anonymous callback function passed in as the second parameter is called with the arguments passed in as the third parameter.

$.ctrl('D', function(s) {
    alert(s);
}, ["Control D pressed"]);

Thats it. I feel it is simple yet effective and solves a common requirement in modern web applications.

What do you think?

Update

A comment provided by “A Nony Mouse” in this blog entry clarified that, we don’t have to store a boolean called “isCtrl” to check if the “Ctrl” key is down while another key is being pressed. It is enough to check for e.ctrlKey as it will return true if the “Ctrl” key is down even if another key is being pressed along with Ctrl. Based on that input the “Ctrl + Key” plugin has been updated. Take a look at the updated code below. For archiving purposes, I am leaving the original version of the code above without any changes.

$.ctrl = function(key, callback, args) {
    $(document).keydown(function(e) {
        if(!args) args=[]; // IE barks when args is null 
        if(e.keyCode == key.charCodeAt(0) && e.ctrlKey) {
            callback.apply(this, args);
            return false;
        }
    });        
};

JQuery: Waiting for Multiple Animations to Complete

Have you ever come across a situation where you wanted to execute a certain piece of code after an animation has completed running? This is a very common use-case in modern web development. jQuery team knows it, and that is why they accept a callback function as argument for every kind of animation call. In the example below, we pass in a callback function that will be executed after the “slideDown” animation is complete. This is the usual scenario.

$("#animateMe").slideDown(function() {
	// This piece of code will be executed 
	// after the animation is complete
});

But, in many other scenarios you might want to wait for multiple animations to complete before executing a certain piece of code. Lets assume that the two elements – “#element1” and “#element2” – are currently getting animated. Our goal is to execute a piece of code after both elements are finished with their respective animations. This is where it gets tricky. I was facing one such challenge today. The solution I have arrived at is to use the “:animated” pseudo-selector and “setInterval” to repeatedly check and wait until the animations have completed running. An example will clarify what I mean

var wait = setInterval(function() {
	if( !$("#element1, #element2").is(":animated") ) {
		clearInterval(wait);
		// This piece of code will be executed
		// after element1 and element2 is complete.
	}
}, 200);

In the example above, I use “setInterval” to repeatedly check if these two elements are NOT being “:animated”. If this condition is not met, then it means that atleast one of them is still getting animated. So, “setInterval” will check for the same condition again in 200 ms until the condition is met. If the condition is met, it means that the animations are complete. So, I immediately do a “clearInterval” and stop checking for this condition again. Any code written after this statement will get executed after both the animations are complete.

Ofcourse, the same code can be modified for more than two elements as well. Some more work, and we can make it handle any number of elements. But, I was wondering if there was an easier, better and more efficient approach to solve the same challenge. If fellow jquery lovers are aware of such solutions please feel free to leave a comment.

LavaLamp for jQuery lovers!

lavalamp-image

Click on the above image to land in the Lava Lamp Demo page. Then, hover over it and feel for yourself, the nifty effect that Lava Lamp offers. What you just experienced is nothing but the LavaLamp menu packaged as a plugin for the amazing jQuery javascript library. I personally believe that the effect rivals that of flash – Don’t you? Especially considering the fact that it is extremely light weight.

Just so you know, it weighs just 700 bytes(minified)!

Often I have noticed, that the credits are usually granted towards the end. Just for a change, i am going to give my credits at the beginning. This effect was originally written by Guillermo Rauch for the mootools javascript library. All I did was to port it for the benefit of jQuery lovers. Thanks Guillermo for inspiring the javascript world with such a nice effect. A special thanks to Stephan Beal who named it “LavaLamp”, and to Glen Lipka for generously helping with the image sprites. Many fellow jQuery lovers also helped shape this plugin with valuable feedback in the mailing list. Thanks a ton, all you guys.

As User Interface developers, we know that one of the first widgets our visitors use is a “Menu”. Capturing their attention right there is something that we always strive for, and I guess LavaLamp is a step in that direction. Before you get bored with all this useless talk, let me get you started on integrating LavaLamp into your jQuery powered site.

I hope you agree that a typical HTML widget consists of 3 distinct components.

  • A semantically correct HTML markup
  • A CSS to skin the markup
  • An unobstrusive javascript that gives it a purpose

Now lets follow the above steps and implement the LavaLamp menu for your site. Remember, In the process of porting from mootools to jQuery, i have simplified both the javascript and CSS for your convenience. So, be informed that you will need to follow the instructions on this page to get the jQuery version running. Follow the instructions on Guillermo Rauch’s page for the mootools version.

Step 1: The HTML

Since most UI developers believe that an unordered list(ul) represents the correct semantic structure for a Menu/Navbar, we will start by writing just that.

        <ul class="lavaLamp">
            <li><a href="#">Home</a></li>
            <li><a href="#">Plant a tree</a></li>
            <li><a href="#">Travel</a></li>
            <li><a href="#">Ride an elephant</a></li>
        </ul>        

In the markup above, “ul” represents the menu, and each “li” represents a menu-item. At this point it is crucial to understand that we will be adding another artificial “li” to represent the background of the currently highlighted menu-item. Since the background itself is cosmetic and doesn’t represent a menu-item, we will be adding it from javascript. Just to make sure we are in sync, “you need not add this li”, the LavaLamp plugin will take care of it. Once added, the “li” representing the background will look like this.

        <li class="back"><div class="left"></div></li>

Step 2: The CSS

You can skin this markup in many different ways to achieve your own personalized menu. The following style sheet is just one possibility. A few more possibilities are demonstrated in the “Bonus” section towards the end of this blog entry.

/* Styles for the entire LavaLamp menu */        
.lavaLamp {
    position: relative;
    height: 29px; width: 421px;
    background: url("../image/bg.gif") no-repeat top;
    padding: 15px; margin: 10px 0;
    overflow: hidden;
}
    /* Force the list to flow horizontally */
    .lavaLamp li {
        float: left;
        list-style: none;                    
    }
        /* Represents the background of the highlighted menu-item. */
        .lavaLamp li.back {
            background: url("../image/lava.gif") no-repeat right -30px;
            width: 9px; height: 30px;
            z-index: 8;
            position: absolute;
        }
            .lavaLamp li.back .left {
                background: url("../image/lava.gif") no-repeat top left;
                height: 30px;
                margin-right: 9px; 
            }
        /* Styles for each menu-item. */    
        .lavaLamp li a {
            position: relative; overflow: hidden;
            text-decoration: none; 
            text-transform: uppercase;
            font: bold 14px arial;
            color: #fff; outline: none;
            text-align: center;
            height: 30px; top: 7px; 
            z-index: 10; letter-spacing: 0; 
            float: left; display: block;
            margin: auto 10px;    
        }

Trust me, this is a simple style sheet. Follow along to understand what is done in each of its sections.

First, we style the “ul” with the bright orange background image and some basic properties like height, width, padding, margin etc. We use relative positioning because, that way we can absolutely position the background “li” relative to the “ul”. This helps by enabling us to move this background “li” freely within the context of the parent “ul”.

Next, we make the “li”s flow horizontally instead of vertically. By default, it flows vertically. There are a couple of techniques to do this. In this case, we are using the “float:left” to achieve this effect.

Next, we style the artifical “li” that represents the background of the currently highlighted menu-item. This uses the sliding doors technique. Also, notice the absolute positioning used as mentioned above.

Finally, we style the anchor that represents the actual clickable portion of each menu-item. These styles are mostly cosmetic and self-explanatory.

Some of the above rules may not be obvious if you are not very confident in how “positioning” works in CSS. For those, i highly encourage you to quickly read this article on CSS positioning. It is short, sweet and very informative.

Step 3: The Javascript

This is the easy part. Most of the javascript work is taken care by the Lava Lamp plugin itself. As a developer, you just have to include the mandatory and/or optional javascript files and fire a call to initialize the menu.

<script type="text/javascript" src="path/to/jquery.js"></script>
<script type="text/javascript" src="path/to/jquery.lavalamp.js"></script>
<!-- Optional -->
<script type="text/javascript" src="path/to/jquery.easing.js"></script>

<script type="text/javascript">
    $(function() { $(".lavaLamp").lavaLamp({ fx: "backout", speed: 700 })});
</script>    

Include a reference to the jQuery library and the LavaLamp plugin. Optionally, include the easing plugin as well. It has many cool effects, that are not contained in the core. For instance, the “backout” effect used in this demo is part of the easing plugin. You can download jQuery here, Easing plugin here, and the LavaLamp plugin here.

Next, in the document.ready event, fire a call to initialize the menu. You have the option to supply an easing “fx” , the “speed” with which the animation happens and a callback to be executed when a menu-item is clicked. They are optional, the default “fx” being “linear” and the default “speed” being “500” ms.

That’s it. At this point you should have a working version of LavaLamp menu for your site.

Bonus

Just with some minor changes in the style sheet, you can get a totally different look n feel for the menu. And yes, the HTML markup and the Javascript remain the same. Click on the image below to experience the demo for this underline-imageless lavalamp.

lavalamp-underline-image

Here is one more variation, again with just some minor changes to the style sheet. I know, they don’t look pretty, but all i am saying is that you are limited only by your imagination. Click on the image below to see the demo for this boxed-imageless lavalamp.

lavalamp-box-image

Finally, for your convenience, i have zipped up all the necessary files into a cohesive package. Download it, and open the demo.html to see all the 3 variations in one page.

Feel free to leave a comment with your feedback, suggestions, requests etc.

Update

Based on popular request, LavaLamp Menu has been updated to support jquery 1.2.x versions. Download the zip file for version 0.2.0 of LavaLamp and open the demo.html to check it out for yourself. Since Firefox 3 has some issues with $(document).ready() function, try using $(window).load() instead if you face any problems. Hopefully a future version of Firefox or jQuery will fix the problem.

jCarousel Lite – A jQuery plugin

jcarousellite-img-02

jCarousel Lite is a jQuery plugin that carries you on a carousel ride filled with images and HTML content. Put simply, you can navigate images and/or HTML in a carousel-style widget. It is super light weight, at about 2 KB in size, yet very flexible and customizable to fit most of our needs.

Did I mention that it weighs just 2 KB?

As if that wasn’t enough, the best part is yet to come… You don’t need any special css file or class name to get this to work. Include the js file. Supply the HTML markup. Then, construct the carousel with just a simple function call.

Visit the project page for more information. There you can find a lot of demos and exhaustive documentation. This blog entry is just a teaser for further exploration.

Installing and getting it to work is as trivial as following the 3 steps given below…

Step 1:

Include a reference to the jQuery library and the jCarouselLite plugin. You can download jQuery here and jCarouselLite here. If you like interesting effects, include the Easing plugin as well (Optional). You may also want to use a compatibility easing plugin if you want to use old easing names. If you would like to navigate the carousel using mouse wheel, then include the mouse-wheel plugin as well (Optional).

<script type="text/javascript" src="path/to/jquery.js"></script>
<script type="text/javascript" src="path/to/jquery.jcarousellite.js"></script>

<!-- Optional -->
<script type="text/javascript" src="path/to/easing.js"></script>
<script type="text/javascript" src="path/to/mousewheel.js"></script>

Step 2:

In your HTML file, provide the markup required by the carousel (a div enclosing an ul). You also need the navigation buttons, but these buttons need not be part of the carousel markup itself. An example follows…

<button class="prev">&laquo;</button>
<button class="next">&raquo;</button>

<div class="any-class">
    <ul>
        <li><img src="image/1.jpg" style="width:150px; height:118px;"></li>
        <li><img src="image/2.jpg" style="width:150px; height:118px;"></li>
        <li><img src="image/3.jpg" style="width:150px; height:118px;"></li>
        <li><img src="image/4.jpg" style="width:150px; height:118px;"></li>
        <li><img src="image/5.jpg" style="width:150px; height:118px;"></li>
    </ul>
</div>

Step 3:

Fire a call to the plugin and supply your navigation buttons. You just managed to architect your own carousel.

$(function() {
    $(".any-class").jCarouselLite({
        btnNext: ".next",
        btnPrev: ".prev"
    });
});

If you have any comments/suggestions/requests, feel free to drop in a comment or reach @ganeshmax in twitter.

 

Update

Based on popular request, jCarouselLite has been updated to support jquery 1.2.x versions. Goto the download page and download version 1.0.1 to enjoy jquery 1.2.x support. Since Firefox 3 has some issues with $(document).ready() function, try using $(window).load() instead if you face any problems. Hopefully a future version of Firefox or jQuery will fix the problem.