MShack
MShack

Reputation: 652

jQuery load div content only when selected

I am planning to set up a lot of tabs that will contain a massive amount of HTML, and I don't won't the page to be slowed down and have all the content loaded to the DOM on page load. So how can I use jQuery to load the div content only when each tab is selected?

HTML would be something like this:

<ul id="nav">
    <li><a href="#content1">Tab 1</a></li>
    <li><a href="#content2">Tab 2</a></li>
    <li><a href="#content3">Tab 3</a></li>
</ul>

<div id="content1">CONTENT</div>
<div id="content2">CONTENT</div>
<div id="content3">CONTENT</div>

Upvotes: 0

Views: 783

Answers (2)

TheStatehz
TheStatehz

Reputation: 310

This would indeed be best achieved using AJAX.

You could store an array of tab content objects and load them based on tab index;

<div id="tabs">
    <ul>
      <li><a href="#content0">Tab 0</a></li>
      <li><a href="#content1">Tab 1</a></li>
      <li><a href="#content2">Tab 2</a></li>
    </ul>

    <div id="content0"></div>
    <div id="content1"></div>
    <div id="content2"></div>
</div>  

<script type="text/javascript">

    var tabcontent = new Array();

    /* Load page */
    tabcontent[0] = $('<div>').load('0.html');

    /* Add content */
    tabcontent[1] = $('<div>').html('Tab content 1');

    /* Add elements */
    tabcontent[2] = $('<div>').html('<div>Tab content 2</div>');

    $('#tabs').tabs({ activate: function(event ,ui) {
            $( '#content' + ui.newTab.index() ).html( tabcontent[ui.newTab.index()].html() );
        }
    });

</script>

See jsFiddle

Upvotes: 1

dmikam
dmikam

Reputation: 1082

You can load neccessary data using Ajax and putting it to your div. By the way, in this case you only need one div for the content.

jQuery(document).ready(function(){
    jQuery('#nav a').click(function(){
        jQuery.get('get_content.php',{
            content: jQuery(this).attr('href').substr(1)
        },function(data){
            jQuery('#content').html(data);
        });
        return false;
    });
});

get_content.php will receive $_GET['content'] == 'content1' or 'content2' or 'content3' depending on which button is clicked, so knowing this you should return necessary content from it.

Upvotes: 0

Related Questions