How to insert Multiple HTML content from a single page

Hello everyone,

I have about 10 JQuery Books and they all talk about using Ajax(JQuery Load function) to insert either an HTML page or fragments of an HTML page into another page.

However, amazingly none of these books mentioned getting multiple items using the same function(document.ready).

Here is what I mean.

I have a document.ready function which I use to get specific content from a page. However, to get additional items, I need to set up additional document.ready function.

So if I was retrieving 3 sets of content from a page, I will set up my script like this:

$(document).ready(function() {
$('.importContent1').click(function () {
$('.importToHere').load('from-this-page.php  #fromThisDivA');
return false;
});
});

$(document).ready(function() {
$('.importContent2').click(function () {
$('.importToHere').load('from-this-page.php  #fromThisDivB');
return false;
});
});

$(document).ready(function() {
$('.importContent3').click(function () {
$('.importToHere').load('from-this-page.php  #fromThisDivC');
return false;
});
});

And the HTML


<a class="importContent1" href="#">Get Content 1</a>
<a class="importContent2" href="#">Get Content 2</a>
<a class="importContent3" href="#">Get Content 3</a>

Is there a leaner better way to do this? Again all the books tells you how to grab a content, which I have done but do I have to create a new function for each item?

Thanks everyone!

IC

You only need one document.ready function. That gets fired once the dom has loaded. So you can wrap everything you want done at that time in that function.

$(document).ready(function() {

$(‘.importContent1’).click(function () {
$(‘.importToHere’).load(‘from-this-page.php #fromThisDivA’);
return false;
});

$(‘.importContent2’).click(function () {
$(‘.importToHere’).load(‘from-this-page.php #fromThisDivB’);
return false;
});

$(‘.importContent3’).click(function () {
$(‘.importToHere’).load(‘from-this-page.php #fromThisDivC’);
return false;
});

});

jQuery has for a long time had a shortcut where instead of using document ready:


$(document).ready(function () {
    ...
});

You can instead make use of the jQuery callback which has existed ever since version 1.0, where you pass the function to the jQuery object to achieve exactly the same result.


$(function () {
    ...
});

Thanks for your time and effort! You truly make a difference.

I was not aware of that but you showed me something new, well new for me. :slight_smile:

IC

Thanks Paul! You’re the MAN!!

IC