Addy
Addy

Reputation: 43

How to make a tab active with a specific URL with JQuery

On my homepage I have a button. That button leads to another page with tabs. How do make one tab active and show it's content whenever that particular button on the homepage is clicked? Is this even possible or must an event take place for this to happen?

if(location.hash) {
        $('#tabbedContent').each(function(){
            $(this).find("#champion" + location.hash.substr(1)).fadeIn();
        });
    } else {
        $('#tabbedContent').each(function(){
            $(this).find(':first-child').fadeIn();
        });
    }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="box">
	<div class="btnList">
		<ul class="btnSet">
			<li>
				<a class="tab linkSection" href="#annual"><span>Nominate a Champion</span></a>
			</li>
			<li>
				<a class="tab linkSection" href="#pathology"><span>Become a Champion</span></a>
			</li>
			<li>
				<a class="tab double linkSection" href="#workshop"><span>Promote the Program</span></a>
			</li>
			<li>
				<a class="tab double linkSection" href="#champion"><span>Contact a Champion</span></a>
			</li>
		</ul>
	</div><!-- meetings tabbed section -->
	<div class="tabbedContent onPage active" id="annual">
		<div class="tabbedContent infoPage">
			<div class="greyBox column col-50">
				<h2>text</h2>
			</div>
			<div class="column col-50">
				<div class="borderBox">
					<h2>text</h2>
				</div><br>
			</div>
		</div>
	</div>
</div>

Upvotes: 1

Views: 312

Answers (1)

Scott Marcus
Scott Marcus

Reputation: 65806

This problem can be solved purely with CSS.

Style all the tabs to not be visible by default and then use the CSS :target pseudo-class to style the active tab as you see fit.

/* All tabs use this class by default */
.tab { opacity:0; position:absolute;} 

/* The active tab will use this rule. It's important that this selector
    is a more specific selector than the default selector, which it is here.  */
.tab:target { opacity:1; transition:1.5s;}
<nav>
  <a href="#tab1">Tab 1</a>
  <a href="#tab2">Tab 2</a>
  <a href="#tab3">Tab 3</a>
  <a href="#tab4">Tab 4</a>
</nav>
<div id="tab1" class="tab">
  <h1>Welcome to Tab 1</h1>
</div>
<div id="tab2" class="tab">
  <h1>Welcome to Tab 2</h1>
</div>
<div id="tab3" class="tab">
  <h1>Welcome to Tab 3</h1>
</div>
<div id="tab4" class="tab">
  <h1>Welcome to Tab 4</h1>
</div>

Upvotes: 1

Related Questions