If your API documentation includes code samples in a few languages, put the samples in tabs and let users select the language they want. Users see samples in their preferred language and you end up with a shorter topic that’s much easier to navigate because it only includes samples your user wants to see.
It’s pretty easy to organize your code samples by tabs. In this example, I’m going to show you how to do it with an open source jQuery plugin called EasyTabs.
HTML
Here’s the basic HTML structure for your tabs.
12345678910111213141516171819
<divclass="tab-container"><ul><!--The div for each code sample needs a unique ID, so we append a number to each --><liclass="tab Java"><ahref="#Java1">Java</a></li><liclass="tab csharp"><ahref="#csharp2">C#</a></li><liclass="tab PHP"><ahref="#PHP3">PHP</a></li></ul><divclass="codeSample Java"id="Java1"><preclass="programlisting"><codeclass="language-java">Java code here</code></pre></div><divclass="codeSample csharp"id="csharp2"><preclass="programlisting"><codeclass="language-csharp">C# code here</code></pre></div><divclass="codeSample PHP"id="PHP3"><preclass="programlisting"><codeclass="language-php">PHP code here</code></pre></div></div>
All your tabs go into a tab-container div. The div contains an unordered list with a list item for each tab that links to the div where the code sample is.
In addition to the HTML markup, there’s some JavaScript to add to the page. JavaScript changes the tab on user click and makes sure that each set of code samples on the page is showing the same language tab.
If you are adding this feature to a single-page help output, you may need to add additional JavaScript to make sure the scroll position stay in the right place as the user changes languages.
$(document).ready(function(){'use strict';//only add tabs if there are multiple languagesif($('div.tab-container').length>0){$('div.tab-container').easytabs({animate:false,updateHash:false});}//switch all code samples to selected language on click$('div.tab-container ul li.tab').click(function(){//get the language from the active link hrefvarcodeLang=$(this).find('a.active').attr('href');//remove number and hash to get lang value without unique identifier.codeLang=codeLang.replace("#","").replace(/\d/g,"");//find and update each set of code samples on the page$('div.tab-container ul li.'+codeLang).each(function(){// make the tab active and hide the other tabs$(this).addClass('active').siblings().removeClass('active');$(this).siblings().find('a').removeClass('active');$(this).find('a').addClass('active');//show the appropriate code sample, hide the others$(this).parent().siblings('div.'+codeLang).addClass('active').css('display','block');$(this).parent().siblings('div.codeSample').not('.'+codeLang).removeClass('active').css('display','none');});});});