I am making a simple slider that works by changing the src attribute of an img tag and the attributes of anchor tags. This is what I have come up with so far:
(function($){
var slides = [
'http://placehold.it/801x350',
'http://placehold.it/802x350',
'http://placehold.it/803x350'
],
titles = [
'Title 1',
'Title 2',
'Title 3'
],
links = [
'http://test1.com',
'http://test2.com',
'http://test3.com'
],
image = $('#stretch-img'),
anchor = $('.featured-title>h2>a');
var interval = setInterval(function() {
image.attr('src', slides[0]);
anchor.attr('href', links[0]);
anchor.html(titles[0]);
}, 3000);
})(jQuery);
I want the interval to loop through the arrays continuously with a simple fade effect. What can be the best way to do this or any way to do this really, coz I’ve got none.
Thanks!
I appreciate all the help.
To loop through your array you can set a current-position-variable and a variable that saves the length of the array:
Then to fade you can fade-out, change the source, then fade-back-in:
This can lead to the image not quite being loaded when the
fadeIn(500)kicks-in, which can be fixed by using an event handler attached to theloadevent for theimageelement:Then you can remove the
fadeIn(500)from the interval function since it will fire when the image has loaded. Theloadevent will fire whenever the source of the image changes and the new source finishes loading.Note that
.on()is new in jQuery 1.7 and is the same as.bind()in this case.