Array item as list and nested list

223 Views Asked by At

I have a set of images for each background page and I am using an array to load each image based on the menu item I click. The menu items have sub menus too and the whole menu system shoudl be in "sync" with the array items:

html menu:

Home (page 1) (menu item hidden but should be "Menu 1" if it would be displayed)

 <ul id="menu">
    <li><a href="page2">Menu 2</a></li>
    <li><a href="page3">Menu 3</a> 
          <ul id="sub-menu">
               <li><a href="page4">Menu 4</a></li>
          </ul>
    </li>
    <li><a href="page5">Menu 5</a></li>
 </ul>

Array:

[0] 1.jpg (image for the home where the menu name item isn't displayed)
[1] 2.jpg (this should be for Menu 2)
[2] 3.jpg (this should be for Menu 3)
[3] 4.jpg (this should be for Menu 4)
[4] 5.jpg (this should be for Menu 5)

When the site loads it reads [0] 1.jpg, which is for the home page. But the first item we can click is "Menu 2" since the "Home" button isn't displayed in the menu it should go to [1] 2.jpg.

This is the jQuery I use:

jQuery (function($) {
  $("#menu .menu li").each(function (index) {
    var item = $(this);
    $("a", item).click(function (e) {
        e.preventDefault();
        api.goTo(index+1);
    });
   });
});

With "api.goTo(index+1);" (using supersized plugin here) I'm saying (or i think I am) on the first click of the menu item, go to index+1 which supposed to be [1] but it isn't, it looks like it is still [0] which is used for the home page tho. Also, i thougth nested items would still follow the index sequence.

Basically I can't get the correct image for the correct page. It's like I'm not navigating the array according to the menu item i click.

P.s. Index in this case is the 0 based index of the item in jquery loop

1

There are 1 best solutions below

4
adeneo On

I have no idea what you're doing, but you are binding click functions inside a loop using a variable, the variable will change, and the result will not be what you expected.

Maybe this will help ?

$('a', 'li').on('click', function(e) {
     e.preventDefault();
     var index = this.href.replace('page', '');
     api.goTo(index);
});

Because of the submenu just getting the right number from the href on click seems easiest.

When referencing values in an array you have do :

var index = ['1.jpg', '2.jpg', '3.jpg'] //an array, starts with zero

var firstimage = index[0]; //this variable is now the string "1.jpg"

I'm guessing you are just passing a number to the api.goTo(number) function, and that function finds the image link in your array, at least that's what it looks like to me ?