seroth
seroth

Reputation: 647

jQuery specific event trigger

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.

Upvotes: 0

Views: 56

Answers (1)

techfoobar
techfoobar

Reputation: 66663

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');

Upvotes: 2

Related Questions