0

I have a unordered list with an event handler attached using jQuery

<ul class='menu'> <li id='1'>Home</li> <li id='2'>item 1</li> <li id='3'>item 2</li> </ul> $('.menu').on('click','li',function(){ console.log($(this).attr('id')); // do navigation stuff }); 

What I want to do is have an event trigger that when I return to this list it automatically selects the option that I selected previously. I have everything else working except this trigger. Any help would be great in guiding me in the right direction. Thanks in advance.

5
  • 4
    What do you mean with "return to this list"? Commented Dec 6, 2013 at 13:37
  • Sorry for being too vague, this is for a menu that has sub menus. What happens is when the user clicks a menu item and then selects a sub menu item it takes them away from the page. I log the option they select but when they come back to the menu, I want them to have that menu option selected and then they just have to choose the submenu item they want to go to next. Hope that made sense. Commented Dec 6, 2013 at 13:39
  • 1
    If you are leaving the page and then returning, you'll need to persist that value somewhere, like a cookie or localStorage, then read the value back in when the page loads. Commented Dec 6, 2013 at 13:40
  • Then the easiest way is to keep record of the element id on the server of in the browser e.g. cookie / localstorage. I would use numerical id's like item1-10 where 1 is main menu id and 10 the submenu id. Then you can select it with $("#item1-10") in jQuery Commented Dec 6, 2013 at 13:41
  • Is this custom menu or using any CMS like Wordpress? Commented Dec 6, 2013 at 13:44

1 Answer 1

2

You can save your selection in a variable and use that to trigger the click on the correct <li>:

var lastSelected = 1; $('.menu').on('click','li',function(){ console.log($(this).attr('id')); // do navigation stuff lastSelected = $(this).attr('id'); //save the id }); 

To trigger the event later, use:

$('#'+lastSelected).trigger('click'); 
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.