troubleshooting Question

CSS Tab, Switch on Page Load based on URL fragment (#hashtag)

Avatar of PRRcomputers
PRRcomputersFlag for United States of America asked on
Web Languages and StandardsJavaScriptCSSHTMLjQuery
5 Comments2 Solutions1392 ViewsLast Modified:
I've got some CSS tabs which are switching via Javascript when clicked. That part is working just fine.  Now, I'd like to have someone land on the page and be taken to a particular tab if they have the appropriate #fragment at the end of their URL.  For example, if they visit they will get the first (default) tab, but if they visit they'll get Tab 2.  That kind of thing.

Tabs are switching beautifully on click, now I just need to tweak this to get the page to activate a particular tab when a particular #hashtag (like above) is used.  I feel like I've done this before, but I'm totally drawing a blank on how.

HTML - the clickable tab headers
<ul class="tabs">
     <li class="active"><a href="#tab1">Tab 1</a></li>
     <li><a href="#tab2">Tab 2</a></li>
     <li><a href="#tab3">Tab 3</a></li>
     <li><a href="#tab4">Tab 4</a></li>

HTML - the tabs themselves
<div class="tab_container">
     <div id="tab1" class="tab_content">
          ... stuff ...
     etc. etc.

$(document).ready(function() {
&#9;//When page loads...
&#9;$(".tab_content").hide(); //Hide all content
&#9;$("ul.tabs li:first").addClass("active").show(); //Activate first tab
&#9;$(".tab_content:first").show(); //Show first tab content

&#9;//On Click Event
&#9;$("ul.tabs li").click(function() {
&#9;&#9;$("ul.tabs li").removeClass("active"); //Remove any "active" class
&#9;&#9;$(this).addClass("active"); //Add "active" class to selected tab
&#9;&#9;$(".tab_content").hide(); //Hide all tab content
&#9;&#9;var activeTab = $(this).find("a").attr("href"); //Find the href attribute value to identify the active tab + content
&#9;&#9;$(activeTab).fadeIn(); //Fade in the active ID content
&#9;&#9;return false;

Can I modify the "When page loads..." section of the Javascript so it activates "tab2" if someone arrives on this page with #tab2 on the end of their URL?  If so, how?
Jon Norman
Information Systems Manager
Join our community to see this answer!
Unlock 2 Answers and 5 Comments.
Start Free Trial
Learn from the best

Network and collaborate with thousands of CTOs, CISOs, and IT Pros rooting for you and your success.

Andrew Hancock - VMware vExpert
See if this solution works for you by signing up for a 7 day free trial.
Unlock 2 Answers and 5 Comments.
Try for 7 days

”The time we save is the biggest benefit of E-E to our team. What could take multiple guys 2 hours or more each to find is accessed in around 15 minutes on Experts Exchange.

-Mike Kapnisakis, Warner Bros