javascript - Image Slider Non working right -


the code below dose not work right. want image slider changes every 5 seconds, if hover on it stop , when leave starts again. when click on it change. can make change every 5 seconds, , change when click, cant stop when hover.

$('document').ready(function() {      var img = 0;     var pic = ['nature', 'grass', 'earth', 'fall', 'fall2'];     var slider = 'img.slide_img'; // html image      function slide() {         $(slider).attr('src', 'pictures/' + pic[img] + '.jpg');         img++;         if (img >= pic.length) {             img = 0;         }     }      $(slider).on('mouseleave', function() {         auto(3000);     });      $(slider).on('click', function() {         slide();     });      function auto(time) {         setinterval(function() {             slide();         }, time)     }    }); 

there's bunch of problems:

  1. you don't initialise setinterval starts when triggering mouseleave event.
  2. every time mouseleave event triggered start new setinterval you'll end having multiple running @ same time.
  3. your desired behaviour hovering on image stop slider, don't have in place that.

how's this: http://jsfiddle.net/byossarian/ulayb/

var img = 0,     pic = ['nature', 'grass', 'earth', 'fall', 'fall2'],     slider = $('img.slide_img'),     timerid = 0,     delay = 2000;  function slide() {     slider.attr('src', 'http://placehold.it/200x200&text=' + pic[img]);     img++;     if (img >= pic.length) {         img = 0;     } }  slider.on('mouseleave', function () {     cleartimeout(timerid);     auto(); });  slider.on('mouseenter', function () {     cleartimeout(timerid); });  slider.on('click', function () {     cleartimeout(timerid);     slide(); });  function auto() {     timerid = settimeout(function () {         slide();         auto();     }, delay); }  auto(); 

notice i'm using 'cleartimeout' prevent multiple timeouts running @ same time:

https://developer.mozilla.org/en-us/docs/web/api/window.cleartimeout


Comments

Popular posts from this blog

java.util.scanner - How to read and add only numbers to array from a text file -

rewrite - Trouble with Wordpress multiple custom querystrings -