I have nested li, which is for horizontal subnav menu. I am trying to get the position of li of child li using jquery’s position() function but it is returning zero always. Same function is working for parent li.
Html Code
<html>
<head>
<title>test</title>
<script type='text/javascript' src='js/jquery-1.4.2.js'></script>
<link rel="stylesheet" href="css/menu_style.css" type="text/css" />
<script>
$(window).load(function() {
jQuery(document).ready(function() {
jQuery('.addchar').live('click', function(event) {
var position = $(this).position();
alert(position.left);
});
});
});
</script>
</head>
<body>
<div id="content">
<div class="menu" id="menu">
<ul>
<li><a href="#" class="addchar">A</a>
<ul>
<li><a href="#" class="addchar">Aword</a></li>
</ul>
</li>
<li><a href="#" class="addchar">B</a>
<ul>
<li><a href="#" class="addchar">Bword </a></li>
</ul>
</li>
</ul>
</div>
</div>
</body>
</html>
CSS CODE
.menu{
border:none;
border:0px;
margin:0px;
padding:0px;
position:relative;/*should be relative*/
font-size:16px;
font-weight:bold;
}
.menu ul{
background:#333333;
height:40px;
list-style:none;
margin:0;
padding:0;
width:900px;
}
.menu li{
float:left;
padding:0px;
width:28px;
font-size:16px;
}
.menu li a{
background:#333333 url("../img/seperator.gif") bottom right no-repeat;
color:#cccccc;
display:block;
font-weight:normal;
font-size:14px;
line-height:35px;
margin:0px;
padding:0px 12px;
text-align:center;
text-decoration:none;
}
.menu li a:hover, .menu ul li:hover a{
background: #2580a2 url("../img/hover.gif") bottom center no-repeat;
color:#FFFFFF;
text-decoration:none;
}
.menu li ul{
background:#333333;
display:none;
height:auto;
padding:0px;
margin:0px;
border:0px;
position:absolute;
width:900px;
float:right;
z-index:200;
}
.menu li:hover ul{
display:block;
}
.menu li li {
background:url('../img/sub_sep.gif') bottom left no-repeat;
display:block;
margin:0px;
padding:0px;
width:36px;
}
.menu li:hover li a{
background:none;
}
.menu li ul a{
display:block;
height:35px;
font-size:14px;
font-style:normal;
margin:0px;
padding:0px 10px 0px 15px;
text-align:left;
}
.menu li ul a:hover, .menu li ul li:hover a{
background:#2580a2 url('../img/hover_sub.gif') center left no-repeat;
border:0px;
color:#ffffff;
text-decoration:none;
}
You mean position in terms of pixels?
.position()gives you the position relative to the offset parent. As each of your menu links is the only child of the parent, the return value will always be zero (if you don’t do some fancy positioning).You might want
offset(), which gives you the position relative to the document.If you want to get the index of the menu item in the set of all menu items, then you need to use
index():