Search code examples
javascriptasp.netglobal-variablesexternal-js

javascript global variable not working with external js file


I have declared the following variable outside of an external js file because part of it is generated server side.

<script type="text/javascript">
     var images=new Array(<%= Master.slideshowArray %>);
</script>

For some reason, by removing this from the external js file (below) the slideshow no longer works... I am guessing I've made an error declaring it as a global variable or perhaps there's something else I need to declare globally... Any ideas?

var nextimage=0;

doSlideshow();

function doSlideshow()
{
    if($('.backgroundImage').length!=0)
    {
        $('.backgroundImage').fadeOut(500,function(){slideshowFadeIn();$(this).remove();});
    }
    else
    {
        slideshowFadeIn();
    }
}

function slideshowFadeIn()
{
    if(nextimage>=images.length) 
        nextimage=0;

    $('.homeLeadContent').prepend($('<img class="backgroundImage" src="'+images[nextimage++]+'" style="display:none;">').fadeIn(500,function() {
        setTimeout(doSlideshow,1000);
    }));
}

Solution

  • Does the script tag for the external js file come before the var images=... inline script tag?

    Browsers execute code in the order that they see them, so if the external js file is seen first, it'll execute the doSlideShow() function which may call the slideshowFadeIn() which would try and references a non-existent-at-that-point images variable.