0

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

John
  • 989
  • 2
  • 16
  • 29
  • 1
    What have you tried so far? Getting the first image element is simply `$('#header img').first()`. As for changing the image: http://stackoverflow.com/questions/10415932/change-jquery-image-src-dynamically/10416038. – Felix Kling Feb 21 '13 at 11:47
  • http://mattgemmell.com/2008/12/08/what-have-you-tried/ – s.lenders Feb 21 '13 at 11:49
  • to get the src you can do `var src = $('#header').attr('src');` then change it at will so only thing left would be to have a timeout function that runs every 8 seconds that pulls the next image src, maybe store all src's in an array or something – martincarlin87 Feb 21 '13 at 11:49
  • do u want to use a slider ? – Sora Feb 21 '13 at 11:52

2 Answers2

1

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)

Arun P Johny
  • 384,651
  • 66
  • 527
  • 531
1

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);
Hugo Alves
  • 1,555
  • 2
  • 18
  • 41