JS-Hero
JS-Hero

Reputation: 317

JQuery - function change images automatically

I need, that some images (for example random 5 - 8 of them) on background will automatically change for another one image (for example after 10 sec, something like that example-link but automatically, not on hover).

  $('.fader').hover(function() {
    $(this).find("img").fadeToggle();
  });

Upvotes: 0

Views: 9548

Answers (3)

rbyrne
rbyrne

Reputation: 193

You can use setInterval to run a function every so often, then inside it have your image changing function

//global variable
var bgImg = 1;

//runs every second
window.setInterval(function(){
    yourFunction();
}, 10000);

//changes background image
function   yourFunction () {
  ++bgImg;

  if(bgImg === 4){
    bgImg = 1;
  }

  if(bgImg === 1){
    $('#element').css("background-image","URL('imgs/image1.jpg')");
  }

  if(bgImg === 2){
    $('#element').css("background-image","URL('imgs/image3.jpg')");
  }

  if(bgImg === 3){
    $('#element').css("background-image","URL('imgs/image3.jpg')");
  }        
}

You can always add some more jquery to fade the image in out or something smoother than a plain switch

Upvotes: 2

fernandosavio
fernandosavio

Reputation: 10387

I made a JSFiddle DEMO.. Maybe it helps you.

It's pretty simple, that's the function that I execute in setInterval

var $imgs = $(".fader").find("img"),
    i = 0;

function changeImage(){
    var next = (++i % $imgs.length);
    $($imgs.get(next - 1)).fadeOut(500);
    $($imgs.get(next)).fadeIn(500);
}
var interval = setInterval(changeImage, 2000);

Hope it help..

Upvotes: 6

writeToBhuwan
writeToBhuwan

Reputation: 3281

is this what you want? Use BX slider.

http://jsfiddle.net/writetobhuwan/Xm2Be/393/

JS is as simple as this..

$(document).ready(function(){
  $('.bxslider').bxSlider();
});

Upvotes: 0

Related Questions