Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript switching to Multiple images onhover

I am trying to make multiple images keep switching on hover (video thumbnail effect) , onhover the images should keep switching through 5 images.

<img id="switch" src="img1.jpg">

$('#switch').hover(function() {
  $(this).attr('src', 'img2.jpg');
}, function() {
  $(this).attr('src', 'img1.jpg');
});

Currently the function can switch the image onhover to another, But what I require is the images to keep switching through 5 images.

  $(this).attr('src', 'img1.jpg');
  $(this).attr('src', 'img2.jpg');
  $(this).attr('src', 'img3.jpg');
  $(this).attr('src', 'img4.jpg');
  $(this).attr('src', 'img5.jpg');

Could this be achieved through a loop? Thanks.

like image 201
Ibrahim Maher Avatar asked Jul 20 '26 03:07

Ibrahim Maher


1 Answers

Create an image array, and a holder variable for clearing interval. Then use setInterval

var imgArr = ['https://pbs.twimg.com/profile_images/604644048/sign051.gif','http://4.bp.blogspot.com/-DAY6ODJU1pw/T9cNFjn46fI/AAAAAAAAFSM/7WD5oM5UugA/s1600/one%2Bsmall%2Bapp.png','http://www.serif.com/_media/img/webplus/x8/new-features/small-feature-two.png','http://images3.moneysavingexpert.com/images/small-claims-court.png','https://encrypted-tbn1.gstatic.com/images?q=tbn:ANd9GcRkVIlZmA_Rb9SW0zsKJ48G3QPgfaeUxdvXqEwmgET-mGCF8Ho-'];
var holder=null;
var index = 1;
$('#switch').hover(function() {
  $(this).attr('src', imgArr[0]);
  var self = $(this);
  holder = setInterval(switchImages,1000);
}, function() {
  clearInterval(holder)
});

function switchImages(){
  if(index==6){
    index=0;  
  }
  $('#switch').attr('src', imgArr[index++]);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
<img id="switch" src="https://encrypted-tbn1.gstatic.com/images?q=tbn:ANd9GcRkVIlZmA_Rb9SW0zsKJ48G3QPgfaeUxdvXqEwmgET-mGCF8Ho-">
like image 178
Anupam Avatar answered Jul 22 '26 18:07

Anupam



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!