I have a div with the ID of header, what id like is the first image found in this id to change every 8 seconds. The image name is image1.jpg and after 8 seconds id like it to change image1 to image2 then after another 8 seconds revert back to image1 and so forth.
Is the route of finding the first image in the div etc a bit long winded and how would i go about the rest? For instance getting the src to change every 8 seconds? Help much appreciated
You can try
var $img = $('div#header img').first();
var flag = false;
setInterval(function(){
$img.attr('src', 'image' + (flag ? 1 : 2) + '.jpeg' );
flag = !flag;
}, 8000);
Functional Demo: Fiddle (Note: This does not work with image, but just a demo for the technique used. Check the console to see the src
value)
assuming the first image is image1.jpeg then at the first run you what it to be 2 so use ++i
to increment first then use the var in the string
var i = 0;
setInterval(function() {
if(i == 2) i=0;
$('#imageID').attr('src', 'image' + (++i) + '.jpeg' );
}, 8000);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.