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:
- you don't initialise
setinterval
starts when triggeringmouseleave
event. - every time
mouseleave
event triggered start newsetinterval
you'll end having multiple running @ same time. - 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
Post a Comment