March 2, 2012

jquery function that load html code into a div and then load other content into div inside html loaded

Question by Raphael D.G

I’d like to know what’s the way to load an html page (page1.html) into a div in webpage active (index.html) and then load another html page (page2.html) into a div that will be inside of page loaded (page1.html). I mean.

index.html

<div id="content"></div>
<a class="link" href="#">load</a>

script

$(document).ready(function() {
    $('a.link').live('click', function() {
        $('#content').load('page1.html', function(){
            $('#content2').load('page2.html');
        });
    });
});

page1.html

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

It’s works fine for only 1 click, at the second click it loads page2.html for 0,5 seconds and then loads page1.html.

What’s the problem ???

Thank you

Answer by Starx

If I am correct, you are trying to load onto the second secontainer, after first container is loaded

Add a simple class on your markup

<div id="content" class="toload"></div>

&

<div id="content2" class="toload"></div>

Now, here is the magical jQuery you need

$(document).ready(function() {
    $('a.link').live('click', function() {
        $('.toload').load('page1.html', function(){
            $(this).removeClass('toload');  //Remove the class so that next time it does not get affected
        });
    });
});

Author: Nabin Nepal (Starx)

Hello, I am Nabin Nepal and you can call me Starx. This is my blog where write about my life and my involvements. I am a Software Developer, A Cyclist and a Realist. I hope you will find my blog interesting. Follow me on Google+

...

Please fill the form - I will response as fast as I can!