user580523
user580523

Reputation:

Load into Div using jQuery

I was looking for a lightweight way of loading external pages into a DIV onClick using jQuery.

For example:

<a href="#" onclick="jQuery Load Function with unique ID 1">Load Page 1</a>
<a href="#" onclick="jQuery Load Function with unique ID 2">Load Page 2</a>
<a href="#" onclick="jQuery Load Function with unique ID 3">Load Page 3</a>
<a href="#" onclick="jQuery Load Function with unique ID 4">Load Page 4</a>

<div id="LoadMe">Where external page will load into</div>

Any help would be really appreciated,

Thanks!

Upvotes: 6

Views: 30640

Answers (4)

Louis Ferreira
Louis Ferreira

Reputation: 75

Thanks for the question, made a small edit. Links within div wiki_links will fetch url and load content in wiki_c (as an alternative to the class for each link):

$("#wiki_links").on('click', 'a', function() {
  $('#wiki_c').load($(this).attr('href'));
  return false;
});

Upvotes: 0

PeeHaa
PeeHaa

Reputation: 72729

<a href="/page1">Load Page 1</a>
<a href="/page2">Load Page 2</a>
<a href="/page3">Load Page 3</a>
<a href="/page4">Load Page 4</a>

<div id="LoadMe">Where external page will load into</div>

$('a').click(function() {
  $('#LoadMe').load($(this).attr('href'));

  return false;
});

You might want to narrow the selector a down though.

Upvotes: 9

Ben Hull
Ben Hull

Reputation: 7673

Any reason you need onclick? If you can point your link to the page you want to fetch from the server, then jQuery's load method does exactly what you want. The simplest way I know of is:

<a href="loadThisPage1" class="pageFetcher">Load Page 1</a>
<a href="loadThisPage2" class="pageFetcher">Load Page 2</a>

<div id="LoadMe">Target div</div>
<script>
    $(function(){
        $('a.pageFetcher').click(function(){
            $('#LoadMe').load($(this).attr('href'));
        });
    });
</script>

Using onclick attributes for events is very out-dated, and definitely at odds with the jQuery patterns for development.

Upvotes: 3

genesis
genesis

Reputation: 50982

<a href="#" onclick="load(1);return false;">Load Page 1</a>
<a href="#" onclick="load(2);return false;">Load Page 2</a>
<a href="#" onclick="load(3);return false;">Load Page 3</a>
<a href="#" onclick="load(4);return false;">Load Page 4</a>

<div id="LoadMe">Where external page will load into</div>
<script>
function load(num){
   $("#LoadMe").load('page'+num+'.php');
}
</script>

http://api.jquery.com/load/

Upvotes: 11

Related Questions