jQuery: AJAX Tabs

Posted by Jetlogs @ 4:11 pm
Category: jQuery,Web Development

One of AJAX’s strengths is that it allows you to save bandwidth for your application by providing data on-demand instead of loading everything in one go. Because of this, some applications like the invisionboard has employed AJAX tabs on its user control panel. But have you ever wondered how to create one yourself? Well this article will show you how its done easily using jQuery.

First of all, the concept of AJAX Tabs is very simple if you would look at it from the ground up. By concept, it is simply multiple AJAX triggers that have the same target container. For this example, we will use a link as the trigger and have a div with an id of tabcontents as the target container.

<a id="tab1" href="#">Tab 1</a><br>
<div id="tabcontent"></div>

First let’s do a sample of a simple AJAX trigger from a link with an id of tab1 loading an HTML page named tab1.html through AJAX. Then the page will be loaded to a div with an id of tabcontent:

$("#tab1").click(function()
{
	$.ajax(
	{
		url: "tab1.html",
		cache: false,
		success: function(message)
		{
			$("#tabcontent").empty().append(message);
		}
	});
});

Its quite simple if you would look at it. The important thing is we have to match the trigger to the page we have to load, and into the container in which we must load the page.

If for example, we want to create a tab with 4 tabs / triggers we can simply manage this through repeating the code above several times and just changing the trigger id’s and the page it loads. The target container will still remain the same. However, this will present a problem since the more tabs / triggers we have, the more the clutter, and the more it is harder to manage.

Fortunately, there is a solution to this. By turning the AJAX call into a function and passing the page required to load as a parameter, we can simplify the tab implementation:

function loadTab(pageUrl)
{
	$.ajax(
	{
		url: pageUrl,
		cache: false,
		success: function(message)
		{
			$("#tabcontent").empty().append(message);
		}
	});
}

$(document).ready(function()
{
	$("#tab1").click(function()
	{
		loadTab("tab1.html");
	});

	$("#tab2").click(function()
	{
		loadTab("tab2.html");
	});

	$("#tab3").click(function()
	{
		loadTab("tab3.html");
	});

	$("#tab4").click(function()
	{
		loadTab("tab4.html");
	});
});

Want to make it even more manageable? Why not use arrays to store the required pages, and pass the array keys instead? And while we’re at it, we can also add a preloader for when the page is still loading. Here is what the final code will look like:

var pageUrl = new Array();
pageUrl[1] = "tab1.html";
pageUrl[2] = "tab2.html";
pageUrl[3] = "tab3.html";
pageUrl[4] = "tab4.html";		

function loadTab(id)
{
	if (pageUrl[id].length > 0)
	{
		$("#preloader").show();
		$.ajax(
		{
			url: pageUrl[id],
			cache: false,
			success: function(message)
			{
			    $("#tabcontent").empty().append(message);
			    $("#preloader").hide();
			}
		});
	}
}

$(document).ready(function()
{
	$("#preloader").hide();

	$("#tab1").click(function()
	{
		loadTab(1);
	});

	$("#tab2").click(function()
	{
		loadTab(2);
	});

	$("#tab3").click(function()
	{
		loadTab(3);
	});

	$("#tab4").click(function()
	{
		loadTab(4);
	});
});

This is merely a bare bones implementation of the AJAX tabs. From here, you can add additional validations (for example AJAX error messages), and add styles to your links and content. You can also specify dynamic content (like PHP, Python, or ASP scripts) as the target for the script to load.

If you want to see a demo of this script in action, or you want to download the source code, just click on the links below:

jQuery AJAX Tabs Demo
Download jQuery AJAX Tabs Source Code


25 Comments »

25 Comments to “jQuery: AJAX Tabs”

  1. Andrew
    1

    Hey thanks for this. I’ve been looking all over the place and couldn’t find what you showed to do here. Thumbs up.

  2. daijun
    2

    Thanks for this.

  3. keithics
    3

    great script. but it can more optimized by using:

    $(document).ready(function() {

    $(“#preloader”).hide(‘slow’);
    $(‘#tab ul li a’).click(function(){

    …..

    rather than using if and else. :)

    thanks again, I am using it on my project.

  4. Tom
    4

    Nice script.. ;)

    How do I set a default tab to load on pageload? ex: I want tab1 to load when page loads. !?!

  5. Jetlogs
    5
    Author Comment

    add this line on your document.ready block:

    
    $(document).ready(function()
    {
        //automatically load tab1 on start
        loadTab("tab1.html"); 
    
        ...
    }
    
  6. Tom
    6

    Love it ;p

    Next item of business. To avoid the page to go to top og page when clicking to load a new tab (when using the tabs long way down on page). Ex: Add 30 times before the navcontainer div, and click tab2. on complete load of tab2, browser windows reset/goes to top of page. Now you have to browse down again to view new content (tab2).

  7. Tom
    7

    Just to let others know, I made it work like this: Enjoy ;p

  8. Tom
    8

    a href=”#” onclick=”return false;”

  9. John
    9

    Are you using jquery Tabs plugin for this or just the base Jquery. I looked at the source code and I don’t see any tabs plugin. Or maybe this article is dated and its probably better to use the Jquery Tabs plugin with Ajax option.

  10. bolo
    10

    cool source,i reprint it!tahnks.

  11. Denny
    11

    I have set this up to load .php pages, however it won’t run php in tab1.php. Any suggestions how I might convert this to run php inside the imported tab pages?

    Great Script!

  12. Brad
    12

    Great script! Thank for sharing. I was wondering how can I pass in a variable to the remote page? Here’s what I’ve tried.
    pageUrl[1] = “tab1.cfm?id=1″;

    I get an error that the variable “id” is undefined. thanks…

  13. Karen
    13

    Hi there,

    I used jquery ui tabs on my site. I know how to disable a tab but I want to find a php or javascript code that will allow me to automatically disable/hide a tab when it is empty. I think I need a conditional statement that says if a tab is empty disable the tab. Am I on the right track? Please help! Thanks.

  14. elena
    14

    How do I set a default tab to load on pageload? ex: I want tab1 to load when page loads. !?!
    I have added this
    {
    //automatically load tab1 on start
    loadTab(“tab1.html”);


    } and not run. this is all code

    var pageUrl = new Array();
    pageUrl[1] = “tab1.html”;
    pageUrl[2] = “tab2.html”;
    pageUrl[3] = “tab3.html”;
    pageUrl[4] = “tab4.html”;

    function loadTab(id)
    {
    if (pageUrl[id].length > 0)
    {
    $(“#preloader”).show();
    $.ajax(
    {
    url: pageUrl[id],
    cache: false,
    success: function(message)
    {
    $(“#tabcontent”).empty().append(message);
    $(“#preloader”).hide();
    }
    });
    }
    }

    $(document).ready(function()

    {
    //automatically load tab1 on start
    loadTab(“tab1.html”);

    }

    {
    $(“#preloader”).hide();

    $(“#tab1″).click(function()
    {
    loadTab(1);
    });

    $(“#tab2″).click(function()
    {
    loadTab(2);
    });

    $(“#tab3″).click(function()
    {
    loadTab(3);
    });

    $(“#tab4″).click(function()
    {
    loadTab(4);
    });
    });

  15. john
    15

    My problem is like this:

    I am using nested tabs but the css for them is not working this is my script.

    Nested jQuery tabs example

    $(function() {
    $(‘#container ul’).tabs();
    });

    var pageUrl = new Array();
    pageUrl[1] = “test.html”;
    pageUrl[2] = “test1.html”;
    pageUrl[3] = “test1.html”;
    pageUrl[4] = “test.html”;

    function loadTab(id)
    {
    if (pageUrl[id].length > 0)
    {
    $(“#preloader”).show();
    $.ajax(
    {
    url: pageUrl[id],
    cache: false,
    success: function(message)
    {
    $(“#tabcontent”).empty().append(message);
    $(“#preloader”).hide();
    }
    });
    }
    }

    $(document).ready(function()
    {

    $(“#preloader”).hide();

    $(“#tab1″).click(function()
    {
    loadTab(1);
    });

    $(“#tab2″).click(function()
    {
    loadTab(2);
    });

    $(“#tab3″).click(function()
    {
    loadTab(3);
    });

    $(“#tab4″).click(function()
    {
    loadTab(4);
    });

    });

    Section 1
    Section 2

    Section 1a
    Section 1b

    Section 2a
    Section 2b

    an I have the same problem as elena :D

  16. Gonzalo
    16

    How to create tab dynamic with json??

  17. Pingback:
    17
    jQuery Ajax Tab for JSP « Prashant's Blog

    [...] a list of tabs, in order to implement it as JSP,AJAX. Among all I found the tab provided by jetlogs to be easy to convert for JSP.  Look was not so attractive, but I changed according to my [...]

  18. sojan
    18

    hey i was just looking for exactly this article.. and glad that i reached here via my google search

    good one :)

  19. Rao
    19

    Hi

    It works great, but I am working on specific requirement, every time I refresh the page, it take me to the first tab. Instead I would like to stay on the current tab every time I reload the page.

    Thanks
    Rao

  20. Commune_killer
    20

    Thanks for the tutorial. I have a requirement to load jsp pages inside the tabs. for example i have jsp1.jsp under tab 1 , when i submit the jsp1.jsp i want the next page to be under the same tab. Can you help me out with this.

  21. fadh
    21

    elena

    use this

    $(document).ready(function() {
    //automatically load tab1 on start
    loadTab(1); //will load tab 1


    });

  22. Joe Ijam
    22

    Hi all

    Thanks for this wonderful simple project.
    Anyway how to combine with form so that while we clicking at another tab, it will save/process the form without having to click submit save/button. Can anyone give me url sample for this….

    Thanks

  23. Marco Berrocal
    23

    YES!!! This is the one I needed, all the other AJAX tabs I have seen rely on menu items to be the ones that control which documents to load (HTML). I wanted to have manual control over this. It’s like a slideshow but a bit better :)

  24. y8 games
    24

    I need it. Thanks for sharing

  25. Lokesh
    25

    Wonderfully Done. Saved many hours. Thanks!!

RSS Comment Feed Comments RSS |trackback TrackBack URI

Leave a comment

  • Archives

  • Donations

  • Social Bookmarks

  • Jetlogs.org
    Some Rights Reserved 2007
    Creative Commons License