phantom phantom - 4 months ago 10
Javascript Question

Changing background images every second jQuery javascript

I am trying to change a background image each second. I have four background images and am able to change them, however, every 4 turns there are 2 images displayed. I cannot figure out the logic as to how to fix this.

My current code can be seen below.

HTML

<img class="img-1" src="one.jpg">
<img class="img-2" src="two.jpg">
<img class="img-3" src="three.jpg">
<img class="img-4" src="four.jpg">


JS

var x = 0,
homepageImages = ["1","2","3","4"];
setInterval(function(){
x++;
if(x === 4){
x = 0;
}
$('.img-' + homepageImages[x]).css('display', 'block');
$('.img-' + (homepageImages[x] - 1)).css('display', 'none');
}, 1000);

Answer

Well in your code it should not do anything

$('.img-' + homepageImages[x]).css('display', 'block');  <-- you show it
$('.img-' + (homepageImages[x])).css('display', 'none');  <-- you hide it

Since you are showing and hiding the same img.

My guess is you removed the -1. In that case, Instead of dealing with the situation where it wraps and on course 0-1 would be -1, hide the image first, than do your addition.

var x = 0,
homepageImages = ["1","2","3","4"];
setInterval(function(){ 
  $('.img-' + homepageImages[x]).css('display', 'none');  //hide the active one first
  x++;
  if(x === 4){
      x = 0;
  }  
  $('.img-' + homepageImages[x]).css('display', 'block');  //show the next one
}, 1000);
Comments