Plugin namespace and img.load function
I'm wrapping up some simple image carousel functions I've put together into a plugin and I'm having some problems when the plugin is invoked by 2 objects on the page. It seems to be a problem with the namespace and I can't work out why it isn't working. I've simplified the code as much as I can. Can anyone tell me why this outputs the right speed variables:
(function($){
$.fn.initCarousel = function(options) {
var defaults = {
speed: 4000
};
//
var opts = $.extend(defaults, options);
//
var target = this;
//
return this.each(function() {
var imgArray = [];
//
target.find('li').each(function(i) {
imgArray.push($(this).find('img').attr('src'));
});
//
alertSpeed = function(){
};
//
loadImage = function(){// load each main image in sequence
//
var nextImage = imgArray[0];
var img = new Image();
//
$(img).load(function () {
alert(opts.speed); // ALERT VARIABLE WITHIN LOAD FUNCTION
}).attr('src', nextImage);
};
//
loadImage();
});
};
})(jQuery);
$(document).ready(function(){
$('#home_carousel').initCarousel({speed: 4000});
$('#feature_b ul').initCarousel({speed: 8000});
});
and this doesn't?
(function($){
$.fn.initCarousel = function(options) {
var defaults = {
speed: 4000
};
//
var opts = $.extend(defaults, options);
//
var target = this;
//
return this.each(function() {
var imgArray = [];
//
target.find('li').each(function(i) {
imgArray.push($(this).find('img').attr('src'));
});
//
alertSpeed = function(){
alert(opts.speed);
};
//
loadImage = function(){
//
var nextImage = imgArray[0];
var img = new Image();
//
$(img).load(function () {
alertSpeed()// ALERT VARIABLE IN SEPERATE FUNCTION
}).attr('src', nextImage);
};
//
loadImage();
});
};
})(jQuery);
$(document).ready(function(){
$('#home_carousel').initCarousel({speed: 4000});
$('#feature_b ul').initCarousel({speed: 8000});
});
Here is the HTML:
<body id="page_home">
<ul id="home_carousel">
<li><img src="images/test.jpg"/></li>
<li><img src="images/test.jpg"/></li>
<li><img src="images/test.jpg"/></li>
<li><img src="images/test.jpg"/></li>
</ul>
<div id="feature_b">
<ul>
<li><img src="images/test.jpg"/></li>
<li><img src="images/test.jpg"/></li>
<li><img src="images/test.jpg"/></li>
<li><img src="images/test.jpg"/></li>
</ul>
</div>
</body>