April 29, 2012

simulate click to view tab when function is run

Question by Michael

I am using the following tabs in a project :

//Tabs
$('ul.tabs').each(function(){

  var $active, $content, $links = $(this).find('a');

  $active = $links.first().addClass('active');
  $content = $($active.attr('href'));

  $links.not(':first').each(function () {
    $($(this).attr('href')).hide();
  });

  $(this).on('click', 'a', function(e){

    $active.removeClass('active');
    $content.hide();

    $active = $(this);
    $content = $($(this).attr('href'));

    $active.addClass('active');
    $content.show();

    e.preventDefault();
  });
}); //End Tabs

and the HTML is as follows:

<ul class='tabs'>
<li><a href='#tab1'>Tab 1</a></li>
<li><a href='#tab2'>Tab 2</a></li>
<li><a href='#tab3'>Tab 3</a></li>
</ul>
<div id='tab1'></div>
<div id='tab2'></div>
<div id='tab3'></div>

The problem I am having is that I want to run a function within the active tab, and then automatically select another tab where the results of the previously executed code will appear.

I am unsure how to go about simulating a click in order to automatically select the next tab, so any help will be greatly appreciated!

Thanks in advance.

Answer by Starx

A simple way to simulate a click, is using .trigger()

$("#tab2").trigger("click"); //when you need in the function
...

Please fill the form - I will response as fast as I can!