soundswaste
soundswaste

Reputation: 3074

Jquery: Run script after ajax load()

I am using the load() function to fetch details dynamically from different pages by clicking on buttons in the menu. One of the buttons point to an image-gallery that uses jquery effects of its own. But those scripts are not running. I tried to load them explicitly using getscript() but that doesnt work either. Here's the code :

$(document).ready(function() {

var hash = window.location.hash.substr(1);
var href = $('#nav li a').each(function(){
    var href = $(this).attr('href');
    if((hash==href.substr(0,href.length-4))&&(hash!='')){
        var toLoad = hash+'.php #content';
        $('#content').load(toLoad);
    }                                           
});

$('#nav li a').click(function(){

    var toLoad = $(this).attr('href')+' #content';
    $('#content').hide();   
    window.location.hash = $(this).attr('href').substr(0,$(this).attr('href').length-4);
    $('#content').load(toLoad,showNewContent());
    function showNewContent() {
        $('#content').fadeIn(1000);
        $.getScript("gallery.js");
    }

    return false;

});

});

Here's the content of my gallery.js file. The exact effect may be irrelevant, I have pasted below code to show the position of my alert-boxes :

$(document).ready(function(){
//perform actions when DOM is ready
  var z = 0; //for setting the initial z-index's
  var inAnimation = false; //flag for testing if we are in a animation
  alert("1");
  $('#pictures img').each(function() { //set the initial z-index's    
    z++; //at the end we have the highest z-index value stored in the z variable
    $(this).css('z-index', z); //apply increased z-index to <img>
    alert("2");
  });

  function swapFirstLast(isFirst) {
    if(inAnimation) return false; //if already swapping pictures just return
    else inAnimation = true; //set the flag that we process a image
    var processZindex, direction, newZindex, inDeCrease; //change for previous or next image
    alert("3");
    if(isFirst) { processZindex = z; direction = '-'; newZindex = 1; inDeCrease = 1; } //set variables for "next" action
    else { processZindex = 1; direction = ''; newZindex = z; inDeCrease = -1; } //set variables for "previous" action

    $('#pictures img').each(function() { //process each image
    alert("4");
          if($(this).css('z-index') == processZindex) { //if its the image we need to process
        $(this).animate({ 'top' : direction + $(this).height() + 'px' }, 'slow', function() { //animate the img above/under the gallery (assuming all pictures are equal height)
          $(this).css('z-index', newZindex) //set new z-index
            .animate({ 'top' : '0' }, 'slow', function() { //animate the image back to its original position
              inAnimation = false; //reset the flag
            });
        });
      } else { //not the image we need to process, only in/de-crease z-index
        $(this).animate({ 'top' : '0' }, 'slow', function() { //make sure to wait swapping the z-index when image is above/under the gallery
          $(this).css('z-index', parseInt($(this).css('z-index')) + inDeCrease); //in/de-crease the z-index by one
        });
      }
    });

    return false; //don't follow the clicked link
  }

  $('#next1 a').click(function() {
      alert("5");
    return swapFirstLast(true); //swap first image to last position
  });

  $('#prev1 a').click(function() {
      alert("6");
    return swapFirstLast(false); //swap last image to first position
  });

});
//Function for z-index based gallery ends here

Here's what I found :

I do a ctrl+F5 and load the page from start, and click the gallery button. I get Alert "1". The images load, but the animation doesnt work.

I click on the gallery button again, without refreshing, and I get all appropriate alerts from 1 to 6 and the effect works like a charm.

When the effect doesnt work, I simply place the content of gallery.js in the chrome-console and click enter, and the effect works perfectly again.

Also, there are times when the effects dont work inspite of repeating the above steps exactly. What could be the problem here? I heard the getscript method is async and I even tried setting ajax sync off but I still get unpredictable results.

Upvotes: 2

Views: 14864

Answers (2)

soundswaste
soundswaste

Reputation: 3074

I found out that despite calling getScript() as a callback to load(), the script loading 'before' the content could which was messing up the flow. Instead of calling showNewContent() as a callback I needed to call showNewContent i.e. a pointer to the function(without round brackets), for it to wait for load to complete. Following code resolved it :

$('#content').load(toLoad,showNewContent);
    function showNewContent() {
        $('#content').fadeIn(1000);
        $.getScript("gallery.js");
}

Upvotes: 7

zb&#39;
zb&#39;

Reputation: 8059

In your gallery js replace

$(document).ready(function(){

with

MyGallery=function(){

In main script :

var MyGallery=function();
$(document).ready(function() {

....

....

  function showNewContent() {
        $('#content').fadeIn(1000);
        $.getScript("gallery.js",{success: MyGallery});
    }

....

....

I not sure what caused you to do such things, better review the idea of yur code flow....

Upvotes: 0

Related Questions