Reputation: 3179
I have a problem with using $.each function between browsers.
I have lists with background-images and if they are finished loading the parent DIV will fadeIn.
I dont know if my code is correctly written (but no js error in console). This code works fine in google chrome but not in Firefox and IE(especially in ver.8 and .9).
HTML:
<ul id="slides">
<li id="slides1"><p><a href="#"><img src="http://placekitten.com/g/200/100" alt=""></a></p></li>
<li id="slides2"><p><a href="#">No.2</a></p></li>
<li id="slides3"><p><a href="#">No.3</a></p></li>
<li id="slides4"><p><a href="#">No.4</a></p></li>
<li id="slides5"><p><a href="#">No.5</a></p></li>
</ul>
sorry 'bout messy code.
JS:
var _imgCounter = 0;
var _parent = $('#slides');
var _child = $('#slides li');
var _childL = _child.length;
var _imgURLArr = [];
var _imgURL;
var _dummyImg;
_child.each(function() {
_imgURL = $(this).css('background-image');
_imgURL = _imgURL.substring(4, _imgURL.length - 1);//omit 'url()'
_imgURLArr.push(_imgURL);
console.log(_imgURL);
});
console.log(_imgURLArr.length);
$.each(_imgURLArr, function(i,val) {
var _tempImg = $('<img/>').attr('src',val);
_tempImg.one('load', function() {
console.log(val + 'is loaded!');
_imgCounter++;
console.log('counter is ' + _imgCounter);
if(_imgCounter == _childL) {
_parent.fadeIn('fast');
}
});
if(_tempImg.complete) {
_tempImg.trigger('load');
}
});
DEMO: http://jsfiddle.net/nori2tae/g8MHs/
I referred to load technique here: http://goo.gl/971A9
This doesn't seem to fire $.each function in FF and IE.
Need some solution.
Thank you.
Upvotes: 1
Views: 1389
Reputation: 6937
Your problem is not with the each
function, but rather the fact the the URL has quotes in it. That is, the value of the string is
"http://dummyimage.com/640x400/0f0/fff.png"
,
and when setting the image URL, Firefox parses it and then treats as a relative URL and tries to access
http://fiddle.jshell.net/nori2tae/g8MHs/show/%22http://dummyimage.com/640x400/0f0/fff.png%22
which results in a 404, which means the load handler is never called.
To fix:
change
_imgURLArr.push(_imgURL);
to
_imgURLArr.push(_imgURL.replace(/"+/g,""));
to eliminate the quotes.
Here's the updated working jsFiddle example
I also suggest adding a handler for when the image fails to load, that would save you some hair pulling when trying to debug your implementation of the script :)
Upvotes: 4