Johnnygirl
Johnnygirl

Reputation: 47

How to load dynamic content (jquery) inside ajax call?

My homepage loads pages with jquery ajax call. In the Pictures subpage there is 3 div, and each loads a php with ajax, too. I would like to include a gallery js to every sub-subpage. However, the js does not loads. Here is my code in the index.php for the subpages:

<script type="text/javascript">
$(function()
{
  var actualmenu = 'fooldal.html';
  $('#tartalom').load('fooldal.html');
  $('.fooldal').click(function()
  {
    $('#tartalom').load('fooldal.html');
    actualmenu = 'fooldal.html';
  }
  );

  $('.kepek').click(function(){
 $('#tartalom').load('kepek.php', function(){
   $(document.body).on('click', 'a[rel=gallery_view]' ,function(){
    $(this).KeViewer('gallery', {'percent' : 70});
    return false;
  });
 });
  actualmenu = 'kepek.php';
 });
});
</script>

And there is my kepek.php page:

<script type="text/javascript">
$(function()
{
  $('#galeria').load('kepek_csenge.php');
  $('#csenge').click(function()
  {
    $('#galeria').load('kepek_csenge.php');
  }
  );
);
</script>

<div id="albums">
    <div class="album" id="csenge">
        Csenge
        <br/>
        <img src="albumok/csenge/01.jpg" alt="csenge"/>
    </div>
</div>
<div style="clear:both;"></div>
<div id="galeria" width="500"></div>

Inside kepek_csenge.php there are rows like this, which should trigger the gallery:

<a class="thumb_wrapper" href="albumok/csenge/01.jpg" title="Első" rel="gallery_view"><img alt="" class="thumb" src="albumok/csenge/thumbs/01.jpg" /></a>

Unfortunately it just loads a new page with the selected picture. How can i use the galleryviewer js in this page?

Upvotes: 1

Views: 909

Answers (1)

charlietfl
charlietfl

Reputation: 171669

It is important to understand that the document you are loading into was ready long before you load anything with ajax

This means that the code wrapped in $(function() in your ajax pages will fire as soon as it is encountered. If that code precedes the html it references then it won't find those elements since they don't exist yet.

Try moving all the script tags in the ajax loaded content to after the html.

It is generally easier to put all the scripts into one and wrap different parts in functions and then just call those functions in the success callback of load();

function loadPage(page){
    var url = '...' +page;
    $('#selector').load(url, function(){
        initViewer();
    });
}

Upvotes: 1

Related Questions