Issue
I need to get the index number of clicked list item, which may nested in another UL.
The code works fine except in the case of nested ULs. Since you are clicking on a parent and a child LI at the same time, it's returning two results. When I tried using the anchor tag instead of LI, the results are -1, because the anchor is inside the LI.
The fiddle: http://jsfiddle.net/4Ww9C/
The code:
(function($) {
var manifest = $('#manifest li');
manifest.click(function(e){
$(this).addClass("active");
manifest.not(this).removeClass('active');
var selected = $(".active");
var pos = manifest.index(selected);
alert (pos);
});
}) ( jQuery );
I'm trying to flatten the hierarchy to create a sequential navigation (slideshow and keybinding will be tied to this index number). So the number that I want is, essentially, the number you would get for the LIs, if the list was flat.
Solution
Events propagate to its parent. You need to stop the propagation, you can use e.stopPropagation()
so that it doesn't navigate to the click event of its parent as well (which is causing multiple alerts).
manifest.click(function (e) {
e.stopPropagation();
.....
Try:
(function ($) {
var manifest = $('#manifest li');
manifest.click(function (e) {
var $this = $(this),
pos;
e.stopPropagation();
manifest.find('.active').not($this.children('a').addClass("active")).removeClass('active');
pos = manifest.index($this);
alert(pos);
});
})(jQuery);
Also if you apply active on li
it will cover the style on all of its children as well, instead you can apply the style on anchors and if you want anchor to cover whole width just provide the style for anchor as display:block
li > a{
display:block;
}
Answered By - PSL
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.