Jump to content

Activating a tab when loading a page


Rob Bedeaux

Recommended Posts

Occasionally, you'll want to open a page and show a tab on the tab element that isn't necessarily the first tab. There isn't a built in way to set the tab when a page loads, but with a little Javascript magic, you can accomplish this. It isn't pretty, but here you go!!

 

Take the code block below and insert it onto the page (I like sticking it on a tab in the tab element so it doesn't get 'lost.'

 

You can now use a query string in the URL to target a specific tab. For example, if I have a tab with three tabs called Red, Blue, and Yellow and I want to target the tab yellow I would input in the URL something like this http://www.mysite.com/mypage/?tab=Yellow.

 

A couple of notes—if you have multiple tabs with the same name, it will set them all to the same tab. Set the Code Element title so you remember what this does!

 

 

<script>
function getParameterByName(name) {
name = name.replace(/[\[]/, "\\[").replace(/[\]]/, "\\]");
var regex = new RegExp("[\\?&]" + name + "=([^]*)"),
results = regex.exec(location.search);
return results === null ? "" : decodeURIComponent(results[1].replace(/\+/g, " "));
}
$j(window).load(function() {
var selectedTab = getParameterByName("tab");
if (selectedTab !== "") {
$j("ul.layoutContainerTabs span a:contains(" + selectedTab + ")").click();
}
})
</script>

 

A couple notes for anyone following along or using the script listed above:

 

  1. Be sure to clear the cache (both from your browser and the Sport Ngin page you just added this code to), otherwise it'll look like it doesn't work.
  2. The query string is case-sensitive. In this case, linking to http://www.mysite.com/mypage/?tab=Yellow will work just fine while http://www.mysite.com/mypage/?tab=yellow will bonk. That is, unless you actually named your tab "yellow" (in lowercase).

 

  • Like 1

Rob Bedeaux (he/him/his)
Director, Partnerships & Symphony Marketing
E rob.bedeaux@nbcuni.com

NBC SPORTS NEXT & FANDANGO

Link to comment
Share on other sites

  • 1 year later...

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
×
×
  • Create New...