jQuery sliding menu revisited

jQuery Sliding Menu Revisited

A few months ago I posted a sliding menu using jQuery and some users asked for a few changes in it: the ability to preload images and making the entire block clickable. So here it is, check the example, a new improved sliding menu based on our favourite JavaScript library, jQuery.

The markup

It will not be different from the previous one, and all the changes will be made in the script and the css style.

[html]

<ul id="iconbar">
<li><a href="#">
<img src="key.gif" alt="" />
<span>Change your password</span>
</a></li>
<li><a href="http://feeds.feedburner.com/ilovecolors&quot; target="_blank">
<img src="rss.gif" alt="" />
<span>Suscribe to our RSS!</span>
</a></li>
<li><a href="#">
<img src="sel.gif" alt="" />
<span>Choose your options!</span>
</a></li>
</ul>

[/html]

As you can see, it’s a simple list with an img and a span tag nested inside an anchor. In the first moment, the span is hidden due to the anchor width.  When mouse rolls over the anchor, we will expand its width to reveal the span.

Style

In order for the span to appear next to the icon, we will position it absolutely. To do so, we will add relative positioning to the li item. We will give the anchor a width of 24px, which is the width of our icon and then a bit of padding to give it some fresh air.

[css]
#iconbar li {
float:left;
position:relative;
overflow: hidden;
margin-right:20px;
background:#E8E8F9;
border: 1px dashed #ffc0ff;
}
#iconbar a {
text-decoration: none;
outline: none;
color:#d00000;
display: block;
width: 24px;
padding: 10px;
cursor:pointer;
}
#iconbar span {
width: 100px;
height: 35px;
position: absolute;
display: none;
line-height:110%;
color:#409BED;
padding-left: 10px;
}
[/css]

Script

The Javascript code for this slide menu adds the image preloading even before the document is ready.

[js]
jQuery.preloadImages = function()
{
for(var i = 0; i<arguments.length; i++)
jQuery("<img>").attr("src", arguments[i]);
}
jQuery.preloadImages("key.gif", "keyo.gif", "rss.gif", "rsso.gif", "sel.gif", "selo.gif");
[/js]

When the document is ready, we attach the hover function to the anchors on the list. When mouse is over an anchor, it will expand its width up to 140px, wide enough to reveal the span and the icon is replaced by the one having its name ending in “o.gif”. In the previous example the original image name was splitted at “.” but this could arise to some issues if the image was being taken from a parent directory like “../image.gif”. In that case the split was performed at the two points.

[js]

jQuery(document).ready(function(){

$("#iconbar li a").hover(
function(){
var iconName = $(this).children("img").attr("src");
var origen = iconName.split(".gif")[0];
$(this).children("img").attr({src: "" + origen + "o.gif"});
$(this).animate({ width: "140px" }, {queue:false, duration:"normal"} );
$(this).children("span").animate({opacity: "show"}, "fast");
},
function(){
var iconName = $(this).children("img").attr("src");
var origen = iconName.split("o.")[0];
$(this).children("img").attr({src: "" + origen + ".gif"});
$(this).animate({ width: "24px" }, {queue:false, duration:"normal"} );
$(this).children("span").animate({opacity: "hide"}, "fast");
});
});

[/js]

You might have noticed that I added a cursor: pointer style to the anchor. Why is that? because in IE6 and 7 when the anchor is expanded, if the mouse is in the new area that wasn’t previously considered within the boundaries of the anchor, the cursor reverts to text cursor.

That’s all we need to finish our sliding menu. Here’s the source file

so you can check it out for yourself.

jQuery(document).ready(function(){$(“#iconbar li a”).hover(
function(){
var iconName = $(this).children(“img”).attr(“src”);
var origen = iconName.split(“.gif”)[0];
$(this).children(“img”).attr({src: “” + origen + “o.gif”});
$(this).css(“cursor”, “pointer”);
$(this).animate({ width: “140px” }, {queue:false, duration:”normal”} );
$(this).children(“span”).animate({opacity: “show”}, “fast”);
},
function(){
var iconName = $(this).children(“img”).attr(“src”);
var origen = iconName.split(“o.”)[0];
$(this).children(“img”).attr({src: “” + origen + “.gif”});
$(this).animate({ width: “24px” }, {queue:false, duration:”normal”} );
$(this).children(“span”).animate({opacity: “hide”}, “fast”);
});
});

80 thoughts on “jQuery sliding menu revisited”

  1. Looks great except the green text shows up before it’s fully loaded (slid out) which is a bit of a cosmetic issue for me.

    Bookmarked for sure though 🙂

  2. Branden: the green text? perhaps you could post a screenshot, including the browser you’re using? thanks

  3. Very nice. You can add overflow:hidden to
    #iconbar li{ } if you want to avoid the text showing over the edge of the block while expanding.

  4. JMCG thanks, I completely overlooked that issue. I’ve added it to the example, the code on the post and the downloaded file.

  5. First of all, I LOVE the all the illustrations & textures on your site! I also love the sliding menu effect & this is a great tutorial. Is it possible to have more than 1 sliding menu on a single page? (I really hope so!)

    I have a similar-looking JQuery menu currently working (based on a different tutorial I found a couple of days ago), but I don’t know how to code the combination hover function so that two menus will work. I’ve been struggling with this for hours! Any tips are much appreciated! Thank you.

  6. Carolyn, thanks for your idea. I will write soon a new tutorial to apply this menu several times in a page.
    Bjorn, are you talking about the Pages widget folding menu?

  7. Hi there,

    I have been trying for the past couple of hours to get this working for me. Originally, i changed the images to my own… and everything worked fine except the buttons wouldnt slide… so then i tried putting the images you used in.. still nothing. Then i downloaded the ZIP file, and didnt change anything except the links of the icons to my links… and still nothing. Then I tried keeping everything exactly the same, and it still didnt work! I checked to make sure my java was enabled… and it was… do you know what could be wrong??

  8. Why preload images with JS when you can use image sprites? This reduces the use of HTTP Requests and speeds up loading.

  9. Thanks very much, this is a great app and it’s perfect for my purposes, except one small thing. Would it be possible to make the slider slide from right too left instead(flip the action) and if so how ?

  10. how can I replace the icons ending in o.gif with other images? What should I change in the general.js script?

    Sorry but I’m not an expert programmer.
    Criss

  11. I have 2 queries.
    1) Is it really necessary to add the “image preload” code line to the beginnign of the javascript? I have noticed that the script works fine even if that line is deleted.
    2) please tell me how to slide the text of the icon to the right

    cheers

    1. Criss, the preload line is neccesary so that no blank spots appears due to the browser loading an image. I could have created the effect using a sprite, but I wanted to show how to preload images using jQuery.
      To slide it to the right you might have to use a different approach with absolute positioning, setting right fixed, and moving the block to the left. Finally, regarding the question you sent me by email, borrar.css is just a reset stylesheet.

  12. Elio, thank you very much for your attention and explanations. I’m not an expert programmer but I’ll figure out how to slide to the opposite direction and will post it here for the community to know. Cheers.

  13. ok, with a little help from a friend I have been able to have the slide to the left.
    Just modify “left” to “right” in the the line:
    #iconbar {position:absolute; top:25%; right:45%; text-shadow:0 1px 0 #eee;}

    Be aware that this only slides the entire block. The goal is also to have the icon description at the left side of the icon. Any help? I’ll keep testing.

  14. ok, if you add #iconbar img {float:right;} to the CSS, the description will slide to the left. The only problem is that the padding is too wide. Can anyone help telling me how to reduce it=

  15. It’s final! To reduce the right padding add text-align:right to #iconbar in CSS, and then fiddle with the widths in #iconbar span and $(this).animate({ width: “140px” }.
    Cheers

    1. hey! thanks for sharing this. I will put it together later to test it and publish it giving you the well deserved credit 🙂 thanks for sharing!

  16. Thanks for this great widget! I am trying to add it in a project of mine.. what I have noticed is that it seems to freeze for a little while the page loads.. is it because of the use of jQuery(document).ready(function()? Is there any way to prevent it from slowing down the whole page loading? Thanx!!!

    1. Dimitris, do you mean that the rollovers are freezed while it’s loading, or the whole page is freezed? If it’s the first case, maybe you could hide them from the stylesheet and show them on document.ready. Otherwise you might want to move your tags to the bottom of the page. The script won’t freeze the page any more than any other tag that you add.

  17. Thanks for the reply Elio! I’m not sure what happens… the page loads but the rollovers don’t work for a while.. it seems like the page waits for the menu to load and then suddenly it works perfectly! How can I hide them from the stylesheet? I tried
    #iconbar a:hover{
    display:none}
    but didn’t work… am I doing something wrong?

  18. OK, it seems to be a hosting server issue eventually! Locally (apache) the page loads perfectly, when I upload it on the server (windows server) the page has the issues I mentioned… I tried on a second server (apache, not local) and the page loads perfectly again! So I guess I have to either change hosting server. or stay with what I get…

  19. Well that is indeed weird. By hiding the menu, I meant that you could add a layer on top of the entire area of the sliding menu and remove it only when the document is ready, like this:
    jQuery(document).ready(function(){ jQuery(".hidinglayer").hide(); });
    In this way, the layer will be hidden once the document is ready. You could add a “Loading…” text or something.
    However, it’s a very weird behaviour and it would be better to solve the core issue.

  20. In the same way than the menu expands to the right when the mouse is over, you could expand your submenu towards the bottom of each parent menu item.

  21. ¡Hola!
    La verdad es que me encanta este efecto, y me gustaría poder incluirlo en mi blog (blogger) para sustituir el diseño de las tabs de la plantilla.
    He tratado de hacerlo, pero no sé donde hay que incluir cada parte del código, en qué situación del código css de la plantilla.
    ¿Podrías hacernos un breve tutorial para novatos, sobre cómo poder poner este tipo de efectos en los tabs?
    ¡Gracias!

  22. Hello, and thanks for a great tutorial!
    I am just about new to everything other than html, but I’ve managed to implement this script to my wordpress-driven blog, but I have one problem:
    The whole animation thing works just perfect the first time I hover them. However – if I hover – the move the cursor outside the box so the animation “goes back to normal” and then hover again, my span-text goes offset, and displays under the icon instead. Take a look here: http://departementet.org/v1/2010/11/04/vi-tar-ansvaret/ if you don’t understand my poor english. (It’s the FB, Twitter and RSS icons just before the comments)

    Again, thank you for this great script!

    1. Harald, for some strange reason, the first time your item is hovered, the span is set to display:inline, which is correct (you can check it on the example here), but then, the span is set to display:block, thus causing the span dropping to the next line. The code is identical so it should work. Maybe some other style that you have might be in conflict? jQuery versions?
      Maybe you could do the following in the script: replace the first occurrence of “fast”, within the first function for the hover() event with:
      { duration: "fast", complete: function(){ jQuery(this).attr( {"style": "display:inline" } ) }
      This will create a new function to be executed when the animation to display the label is finished. That function will force the span display to inline.

  23. Don’t work on my site. (Unless I am missunderstanding something, that is). I replaced this:
    function(){ var iconName = jQuery(this).children("img").attr("src"); var origen = iconName.split(".png")[0]; jQuery(this).children("img").attr({src: "" + origen + "h.png"}); jQuery(this).css("cursor", "pointer"); jQuery(this).animate({ width: "145px" }, {queue:false, duration:"fast"} ); jQuery(this).children("span").animate({opacity: "show"}, "fast"); },
    with this:
    function(){ var iconName = jQuery(this).children("img").attr("src"); var origen = iconName.split(".png")[0]; jQuery(this).children("img").attr({src: "" + origen + "h.png"}); jQuery(this).css("cursor", "pointer"); jQuery(this).animate({ width: "145px" }, {queue:false, duration:"fast" complete: function(){ jQuery(this).attr( {"style": "display:inline" } ) }} ); jQuery(this).children("span").animate({opacity: "show"}, "fast"); },

    – is that what you ment?
    All that results in is that there is no animation at all.

    And also, I am not using any other jQuery on the site. And the version I am using is v.1.4.3

  24. Harald, replace the first occurrence. In the code you pasted above, check line 11, that says
    "show"}, "fast");
    Replace the fast that appears there with the code I gave you in my previous comment. Leave the rest as it was before 😀

  25. Sorry, still nothing. I am new to jQuery and all, so I tried “everything” hehe – I tried replacing:

    fast
    “fast”
    , “fast”
    , “fast”)
    “fast”)
    …and nothing worked 🙁

    1. no prob buddy, try this
      jQuery.preloadImages = function() { for(var i = 0; i<arguments.length; i++) jQuery("").attr("src", arguments[i]); } jQuery.preloadImages("key.gif", "keyo.gif", "rss.gif", "rsso.gif", "sel.gif", "selo.gif"); jQuery(document).ready(function(){ $("#iconbar li a").hover( function(){ var iconName = $(this).children("img").attr("src"); var origen = iconName.split(".gif")[0]; $(this).children("img").attr({src: "" + origen + "o.gif"}); $(this).css("cursor", "pointer"); $(this).animate({ width: "140px" }, {queue:false, duration:"normal"} ); $(this).children("span").animate({opacity: "show"}, { duration: "fast", complete: function(){ jQuery(this).attr( {"style": "display:inline" } ) }); }, function(){ var iconName = $(this).children("img").attr("src"); var origen = iconName.split("o.")[0]; $(this).children("img").attr({src: "" + origen + ".gif"}); $(this).animate({ width: "24px" }, {queue:false, duration:"normal"} ); $(this).children("span").animate({opacity: "hide"}, "fast"); }); });

      it should work 😀

  26. Nope 🙁
    I REALLY appreciate your help, but it just don’t seem to work for me, hehe. I copied your script right from the reply here now, only changing the imagenames (and .gif to .png) but it still won’t work. No animation what so ever 🙁
    But don’t worry – please don’t waste anymore time on support, hehe, I’ll figure out something else 🙂

Leave a Reply