I’m rather new to jQuery and I’m trying to make a cool little menu effect where when the user hovers over a element (#nav li) it will animate to a larger width, which will reveal the full background image. Each of the menu items has a ID to explicitly set a width (since they are all different in size), so #nav1 might be 80px whereas #nav2 is 90px. So I found this: How to get all of the IDs with jQuery? and that helped me to create a array but now I’m having problem figuring out how to insert it into the animation. I figured I would need to do a each or for loop. But like I said I’m rather new to jQuery and am having some problems.
So basically I’d like the variable chgWidth to return the width() of the currently hovered #nav and then I would plug that variable into the animate except I would add 30px for instance, or on the hover off I would subtract 30px.
Any idea? Here is my current code…
$(function(){
var chgWidth = $("#nav [id]").map(function(id) {
return this.id;
});
$.each(chgWidth,function(n,value){
$('#nav li').hover(function() {
$(this).stop(0,1).animate({"width" : chgWidth+"px" });
},
function(){
$(this).stop(0,1).animate({ "width" : chgWidth+"px" });
});
});
Sample HTML
<div id="menu">
<ul id="nav">
<li id="nav1"><a alt="" href="#">home</a></li>
<li id="nav2"><a alt="" href="#">about us</a></li>
<li id="nav3"><a alt="" href="#">weddings & events</a></li>
<li id="nav4"><a alt="" href="#">gallery</a></li>
<li id="nav5"><a alt="" href="#">accolades</a></li>
<li id="nav6"><a alt="" href="#">blog</a></li>
<li id="nav7"><a alt="" href="#">contact us</a></li>
</ul>
</div>
Sample CSS:
#menu { width: 100%; overflow: hidden; padding:0px 0px; background: #ffc4a0;}
#nav { position: relative; left: 50%; float: left;}
#nav li { position: relative; right: 50%; float: left; padding: 0 5px; margin: 0 5px; overflow:hidden; }
#nav1 { width:55px; }
#nav2 { width:80px; }
#nav3 { width:175px; }
#nav4 { width:60px; }
#nav5 { width:85px; }
#nav6 { width:40px; }
#nav7 { width:100px; }
#nav li a { color: #ffffff; text-decoration: none; font: bold 16px Verdana, Arial, Helvetica, sans-serif; }
Based on the answer I got this is what I ended up doing and it seems to work good (Thanks to Joel and krdluzni):
$(function(){
$("#nav [id]").each(function(){
$(this).hover(function() {
$(this).stop(0,1).animate({"width" : "+=30" });
},
function(){
$(this).stop(0,1).animate({ "width" : "-=30" });
});
});
});
You don’t actually need to get the ids in an array so much as you need to assign an animation to each element in nav that has an id.
Instead of mapping the ids to your chgWidth variable, use each to iterate over the collection of elements and set each one individually.
When you use
eachto iterate over a collection of elements, thethiscontext is set to the current iterating element.