jQuery: Lavalamp menu tutorial

In this post I'd like to show you how to implement a Lavalamp-like effect on a menu from scratch. As you will see, all you need is some basic CSS declarations and just a few lines of jQuery code. I recommend you to test the proposed solution also in Internet Explorer and report any problem in the post's comment. Let's get to work.

Lavalamp: A definition

A Lavalamp effect is simply made by an empty element with a declared background color that follows the mouse position when you move it through the items of a menu. In other words, it consists of a simple cursor that changes its left offset when you change your mouse position moving from an item to another.

The markup

Here's a simple navigation menu:

<div id="navigation">

  <li><a href="#">Home</a></li>
  <li><a href="#">About</a></li>
  <li><a href="#">Contacts</a></li>



We'll use contextual positioning to exactly position our cursor on the menu and let it free to move horizontally:

body {
 margin: 0;
 padding: 0;
 font: 100% Arial, sans-serif;

#navigation {
 height: 2em;
 padding: 0 1em;
 border-bottom: 1px solid #c34545;
 position: relative;

#navigation ul {
 margin: 0;
 padding: 0;
 list-style: none;
 height: 100%;

#navigation li {
 float: left;
 height: 100%;
 margin-right: 0.5em;

#navigation a {
 float: left;
 height: 100%;
 padding: 0 1em;
 color: #d34545;
 font-weight: bold;
 text-transform: uppercase;
 text-decoration: none;
 line-height: 2;

#navigation a:hover {
 color: #a34545;

#navigation #lava {
 background: #e5e5e5;
 height: 100%;
 overflow: hidden;
 position: absolute;
 top: 0;
 left: 0;
 width: 0px;
 z-index: -1;

The lava element has a zeroed width and a negative z-index value so that its background color will appear just under each item. I'm not sure if this solution works in Internet Explorer because I can't test it right now, so be careful.

The jQuery code

With jQuery, we need the actual width of each menu item and its left offset to give the exact dimensions and coordinates to our cursor:

$(function() {

  $('<div id="lava"/>').appendTo('#navigation');
  $('li', '#navigation').each(function() {
    var $li = $(this);
    var $a = $('a', $li);
    var left = $a.position().left;
    var width = $a.outerWidth();
    $a.mouseover(function() {
      $('#lava').css('width', width).
      stop(true, true).
        left: left
      }, 'slow');


You can see the demo below.


Live demo

This entry was posted in by Gabriele Romanato. Bookmark the permalink.

Leave a Reply

Note: Only a member of this blog may post a comment.