javascriptjquerytabsjquery-ui-tabs

Tabs not shown when #id is in page URL


I tried to add a tabs option to my page URL so that the specified tab is focused when the page loads

Example: mywebsite/page/#tab3

I'm using jQuery, but not jQuery UI.

Any ideas om how I can do it?

<div class="wrapper">

<ul class="tabs clearfix" data-tabgroup="first-tab-group">
  <li><a href="#tab1" class="active">Tab 1</a></li>
  <li><a href="#tab2">Tab 2</a></li>
  <li><a href="#tab3">Tab 3</a></li>
</ul>

<section id="first-tab-group" class="tabgroup">
  <div id="tab1">
    <h2>Heading 1</h2>
    <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Nulla deserunt consectetur ratione id tempore laborum laudantium facilis reprehenderit beatae dolores ipsum nesciunt alias iusto dicta eius itaque blanditiis modi velit.</p>
  </div>
  <div id="tab2">
    <h2>Heading 2</h2>
    <p>Adipisci autem obcaecati velit natus quos beatae explicabo at tempora minima voluptates deserunt eum consectetur reiciendis placeat dolorem repellat in nam asperiores impedit voluptas iure repellendus unde eveniet accusamus ex.</p>
  </div>
  <div id="tab3">
    <h2>Heading 3</h2>
    <p>Atque ratione soluta laboriosam illo inventore amet ipsum aliquam assumenda harum provident nam accusantium neque debitis obcaecati maxime officia saepe ad ducimus in quam libero vero quasi. Saepe sit nisi?</p>
  </div>
</section>

</div>
$('.tabgroup > div').hide();
$('.tabgroup > div:first-of-type').show();
$('.tabs a').click(function(e){
  e.preventDefault();
    var $this = $(this),
        tabgroup = '#'+$this.parents('.tabs').data('tabgroup'),
        others = $this.closest('li').siblings().children('a'),
        target = $this.attr('href');
    others.removeClass('active');
    $this.addClass('active');
    $(tabgroup).children('div').hide();
    $(target).show();
})    

Solution

  • $(document).ready(function(){
      if (document.location.hash != '') {
        $(".active").removeClass("active");
        $('a[href*="' + document.location.hash + '"]').addClass("active");
        $('[id^=tab]').hide();
        $(document.location.hash).show();
      }
    });