user6002037
user6002037

Reputation:

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);

Upvotes: 1

Views: 148

Answers (2)

henrybbosa
henrybbosa

Reputation: 1125

just edited your code try this:

use '==' instead of '===' because tripple equals will check the type; also dont increment before. increment after because javascript arrays start at index 0 remember the the homepages array is an array of strings using 'x===4' will return false and also homepages[0] == '1' so incrementing before wont give you first image

<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">

var x = 0;
var 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');
     x++;
}, 1000);

Upvotes: 0

epascarello
epascarello

Reputation: 207501

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);

Upvotes: 1

Related Questions