1. Code
  2. JavaScript
  3. jQuery

Creating a Floating HTML Menu Using jQuery and CSS

Scroll to top

For all of us who deal with long web pages and need to scroll to the top for the menu, here's a nice alternative: floating menus that move as you scroll a page. This is done using HTML, CSS and jQuery, and it's fully W3C-compliant.

Demo and Source

You can see a demo of this tutorial by clicking on the "Demo" button above. For the source download, please note that the jQuery library, Dimensions plugin, and Eric Meyer's Reset code are not in the ZIP file.

What We're Building

This tutorial covers how to create a "floating menu" using HTML, CSS, and jQuery. To reiterate, a floating menu stays visible even if you scroll down a web page. They're animated, so they move up and down as you scroll the browser window up or down. I am going to show you how to make a floating menu using jQuery and CSS, and hopefully make some new jQuery disciples :D.

Before we continue to the coding steps, have a look at the two screen snaps below. The first shows a web page with a floating menu at top right. Of course, you can't tell it's floating until you see it live and actually scroll the page. So look at the second snapshot, and you can see that the menu has moved.

Step 1

Let's start with the HTML markup for a nice menu consisting of three sub-menus:

1
    <div id="floatMenu">
2
        <ul>
3
            <li><a href="#" onclick="return false;"> Home </a></li>
4
        </ul>
5
        
6
       <ul>
7
            <li><a href="#" onclick="return false;"> Table of content </a></li>
8
            <li><a href="#" onclick="return false;"> Exam </a></li>
9
            <li><a href="#" onclick="return false;"> Wiki </a></li>
10
        </ul>
11
        
12
        <ul>
13
            <li><a href="#" onclick="return false;"> Technical support </a></li>
14
        </ul>
15
    </div>

This is the basic markup we will use. The main part in this bit of HTML is the <div id="floatMenu">...</div> in Line 01, which encapsulates the whole menu. The three lists are only used to demonstrate structure, which can be modified to suit your needs. In this case, there are three sections to the menu, as represented by three unordered HTML lists.

As a matter of habit, I disable the click on dummy links (href="#"). Just to be sure that a click on a dummy link doesn't send the page back to the top, there is also an onclick="return false;" in <a href>. This method allows to add menu item features such as lightboxing - something that requires the page to stay at its current vertical position when the user clicks on a menu link.

Step 2

Now we need some CSS rules to skin and position the menu. (I used Eric A. Meyer's CSS Reset, so that's why there is no margin:0 or padding:0 on the ul element):

1
body {
2
    background-color:#000;
3
    height:2000px;
4
    color:#ccc;
5
    font:10px "Lucida Grande", "Lucida Sans", "Trebuchet MS", verdana, sans-serif;
6
}
7
#floatMenu {
8
    position:absolute;
9
    top:150px;
10
    left:50%;
11
    margin-left:235px;
12
    width:200px;
13
}
14
#floatMenu ul {
15
    margin-bottom:20px;
16
}
17
#floatMenu ul li a {
18
    display:block;
19
    border:1px solid #999;
20
    background-color:#222;
21
    border-left:6px solid #999;
22
    text-decoration:none;
23
    color:#ccc;
24
    padding:5px 5px 5px 25px;
25
}

The body height (Line 03, above) has been set only to get enough room for our menu to scroll up and down with the page. This should be removed in a real case scenario. The two other things to take note of are the position:absolute (Line 08) and the left:50% (Line 10), both in the #floatMenu CSS rule (Line 07), above.

The "position" attribute is used when you need to remove an element from the flow of the document and keep it at a precise place in your page. If you use the text zoom function of your browser, an element with absolute positioning will not move, even if the text around it increases in size.

The "left" attribute is used to position the specific div element horizontally. The value needs to be defined as a percentage in the case that we want a centered design. With a 50% value, the left side of the container is positioned in the middle of the page. To position it left or right we need to use the "margin-left" attribute (Line 11), with a negative value for an offset to the left and a positive one for an offset to the right.

The others elements in the above stylesheet rules customize the visual design.

Step 3

Now we have a menu of three sections positioned in the upper right hand side of the page. To enhance the menu item roll-over effect, let's add style classes menu1, menu2 and menu 3 to each menu section, respectively (to each <ul> element). We will have 3 distinct sub-menus using our 3 <ul> tags. The code below is a modification of the HTML code shown in Step 1 above:

1
    <div id="floatMenu">
2
        <ul class="menu1">
3
            ...
4
        </ul>
5
        
6
       <ul class="menu2">
7
           ...
8
        </ul>
9
        
10
        <ul class="menu3">
11
          ...
12
        </ul>
13
    </div>

Now let's define some CSS hover-based roll-over effects, which will be different for each menu section.

1
    #floatMenu ul.menu1 li a:hover {
2
        border-color:#09f;
3
    }
4
    #floatMenu ul.menu2 li a:hover {
5
        border-color:#9f0;
6
    }
7
    #floatMenu ul.menu3 li a:hover {
8
        border-color:#f09;
9
    }

Now each menu section will display a different color when the mouse hovers over a menu item. If you like, you can also add rules for other menu link states using :link, :visited, :hover and :active pseudo classes. The order in which you should write them can be easily memorized like this: LoVe and HAte, where the capitalized letters represents the first letter of each state.

Step 4

We've got a nice looking menu and could stop here, but we do want that floating menu, so it's time to add some jQuery. You'll need to download the jQuery library and the Dimensions plugin. This plugin will be used to grab information about the browser's window (width, height, scroll, etc.). You can link to both bits of jQuery code from your HTML file in the <head>...</head> section. Just remember to change the URL path according to where on your server you place the jQuery library and plugin files.

1
    <script language="javascript" src="jquery.js"></script>
2
    <script language="javascript" src="jquery.dimensions.js"></script>

We'll need some custom jQuery code as well, so start a new <script> section, also within the <head>...</head> section of your HTML document:

1
    <script language="javascript">
2
		...
3
    </script>

Add the following jQuery code inside the the <script> section:

1
    $(document).ready(function(){
2
        // code will go here

3
    });

The $(document).ready() function is similar to the window.onLoad but improved. With the window.onLoad function, the browser has to wait until the whole page (DOM and display) is loaded. With the $(document).ready() function, the browser only waits until the DOM is loaded, which means jQuery can start manipulating elements sooner.

Step 5

We need a listener for the "scroll page" window event. Our custom jQuery script now looks like this:

1
	
2
    $(document).ready(function(){
3
        $(window).scroll(function () { 
4
            // code will go here

5
        });
6
    });

A listener is an event handler waiting on standby for a particular window event to happen - in this a page scroll up or down.

Step 6

Since our menu will "float" as the page is scrolled, we need to track its initial position. Instead of hard-coding that into the jQuery, we'll read it's position using the Dimensions jQuery plugin, then use the retrieved value. We will do the same with the name of our menu. Let's add two variable definitions (Lines 01, 02) so that our code now looks like this:

1
2
    var name = "#floatMenu";
3
    var menuYloc = null;
4
	
5
    $(document).ready(function(){
6
        menuYloc = parseInt($(name).css("top").substring(0,$(name).css("top").indexOf("px")))
7
        $(window).scroll(function () { 
8
            // code will go here

9
        });
10
    });

Lines 01 and 02 define variables "name" and "menuYloc". Line 05 sets the value of "menuYloc". The "name" variable will be used to reference our floating menu. The "menuYloc" variable will contain the original vertical position of our menu.

Let's look at how the value of menuYloc is set in Line 05. This statement is an example of jQuery's powerful function-chaining. First we read the "top" attribute value from the CSS rules of our menu element (which is "150px", set in Step 2). Then we strip off the "px" string at the end, since we only need the "150" part. To do this, the jQuery function call .css("top") first finds the value of the top attribute for the menu. (This attribute was set in Line 09 of the code in Step 2, above.) That results in retrieving the value "150px". Then the .indexOf() function finds where the "px" in "150px" starts, and the .substring() function ensures we save everything before the "px". The .parseInt() function turns the string "150" into an numeric integer value.

Step 7

We now arrived at the fun part of this tutorial: animating the menu to make it "float". To do this, we need to determine how far the page has scrolled in pixel dimension. We have the original menu location stored in variable "menuYloc". We need the offset of the scroll bar, which we can get from the command $(document).scrollTop(), defined in the Dimensions jQuery plugin. After grabbing the offset we can add the animate command. Lines 07 and 08, below, show the new code:

1
    var name = "#floatMenu";
2
    var menuYloc = null;
3
	
4
    $(document).ready(function(){
5
        menuYloc = parseInt($(name).css("top").substring(0,$(name).css("top").indexOf("px")))
6
        $(window).scroll(function () { 
7
            var offset = menuYloc+$(document).scrollTop()+"px";
8
            $(name).animate({top:offset},{duration:500,queue:false});
9
        });
10
    });

The variable "offset", in Line 07 above, contains the difference between the original location of the menu (menuYloc) and the scroll value ($(document).scrollTop()), in pixel measurement. To make it work as a CSS rule, we add the necessary measurement unit, "px", after the numeric value. Now we can apply the vertical offset, as calculated, to position the menu and thus making it move.

To make it all look nicer, let's make use of jQuery's animation options. We've stored the menu name in the variable "name" and can recall it when needed, to use it along with the .animate() function. The animate function requires two parameters: (1) the style properties, and the (2) animation options. In this tutorial, we just need to animate the "top" CSS property, but to specify additional parameters, separate each property:value pair with a comma (,).

We're using two parameters here. The "duration" is the length of the animation
in milliseconds, and the "queue" is a list of all positions we want our object to be animated to. Since we only want to animate our object to its final location (the browser's current scroll location), we set "queue" to false.

We should now have a functioning floating menu.

Did you find this post useful?
Want a weekly email summary?
Subscribe below and we’ll send you a weekly email summary of all new Code tutorials. Never miss out on learning about the next big thing.
Looking for something to help kick start your next project?
Envato Market has a range of items for sale to help get you started.