Building jQuery Tabs That Open & Close

Building jQuery Tabs That Open & Close

jQuery is obviously a really powerful tool. If you’ve done any work with it, you don’t need convincing. My latest project involving jQuery was a bit tricky because I couldn’t find anything that detailed how to generate a tab once a user clicked on a link, and then how to close that tab if the user clicked the close button. Here is my setup:

I needed to create a page with some static links, that when clicked on would spawn a new tab.

The content area for each tab would contain a Close button that would remove the tab and hide the div contents. I didn’t want the div contents removed because I wanted users to be able to open the tabs again if they wanted to.


<div id="mytabs">
<ul>
<li><a href="#tabs-home">My Projects Home</a></li>
</ul>
<div id="tabs-home">
<h3>Welcome to My Projects Home</h3>
<p><a href="#" onclick="showTab('myActiveProjects', 'My Active Projects')">My Active Projects</a></p>
<p><a href="#" onclick="showTab('mySalesActivities', 'My Sales Activities')">My Sales Activities</a></p>
</div>
</div>
<div id="tabs-myActiveProjects" style="display:none;">
<h3>My Active Projects</h3>
<p><input type="button" name="killTab" value="Close" onclick="hideTab('myActiveProjects')" /></p>
</div>
<div id="tabs-mySalesActivities" style="display:none;">
<h3>My Sales Activities</h3>
<p><input type="button" name="killTab" value="Close" onclick="hideTab('mySalesActivities')" /></p>
</div>

Wiring Up The Javascript


function init()
{
$("#mytabs").tabs();
}

function showTab(tabID, tabName)
{
currentTabID = tabID;

// this will add a tab via the standard method
$("#mytabs").tabs("add","#tabs-" + tabID, tabName);
$("#tabs-" + tabID).css("display","block");

$("#mytabs").tabs('select', tabID);
}

function hideTab(tabID)
{
$("#tabs-" + tabID).css("display","none");
$("a[href^=#tabs-"+ tabID +"]").parent().remove();
$("#mytabs").tabs('select', 0);
}

$(document).ready(init);

Don’t forget to include the jQuery UI JS file and the corresponding CSS. You’ll also need to include the jQuery JS file as well. If you have any troubles with this, drop me a note.


<script type="text/javascript" src="jquery-1.3.2.min.js"></script>
<script type="text/javascript" src="jquery-ui-1.7.2.custom.min.js"></script>
<link type="text/css" href="styles/smoothness/jquery-ui-1.7.2.custom.css" rel="stylesheet" />

My next step with the above is to relocate the Close button so that it is an ‘X’ image on the tab itself that when clicked on would close the tab. I’ll update once I figure that out! Good times!


If you have better solution, just tell me !

0 comments:

Post a Comment