0
votes

I am using the following jquery code for a simple tab view where if you click a tab it will display a div specific to that tab. This only works when clicking tabs inside the ul.tabs property. How could I adjust the code to also allow for a link on the same page outside the ul.tabs list to show any div I want?

    $(document).ready(function(){
    $('ul.tabs').each(function(){
        // For each set of tabs, we want to keep track of
        // which tab is active and it's associated content
        var $active, $content, $links = $(this).find('a');

        // Use the first link as the initial active tab
        $active = $links.first().addClass('active');
        $content = $($active.attr('href'));

        // Hide the remaining content
        $links.not(':first').each(function () {
            $($(this).attr('href')).hide();
        });

        // Bind the click event handler
        $(this).on('click', 'a', function(e){
            // Make the old tab inactive.
            $active.removeClass('active');
            $content.hide();

            // Update the variables with the new link and content
            $active = $(this);
            $content = $($(this).attr('href'));

            // Make the tab active.
            $active.addClass('active');
            $content.show();

            // Prevent the anchor's default click action
            e.preventDefault();
        });
    });
});

Here is the html:

            <ul class="tabs">
          <li><a href="#photo_tab">Photos</a></li>
        </ul>
        <div id="photo_tab" class="tabcontent">
          <h3>Section 1</h3>
          <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Donec lobortis placerat dolor id aliquet. Sed a orci in justo blandit commodo. Vestibulum ante ipsum primis in faucibus orci luctus et ultrices posuere cubilia Curae.</p>
        </div>

So I would like to use href="#photo_tab" on a link somewhere else on the page that will bring up the photo_tab div and show the active tab.

1

1 Answers

0
votes

You can manually fire the click trigger on the correct tab.

HTML:

<div class="extlink" data-tabid="photo_tab">click me!</div>


<ul class="tabs">
   <li><a href="#photo_tab" id="photo_tab">Photos</a></li>
</ul>

JS:

$('.extlink').click(function(){
    var tabid = $(this).attr('data-tabid');    // this gets the id of the element you want to trigger
    $('#'+tabid).click();   /// this acts as if you clicked on that tab element
});