November 3, 201411 yr Good evening! I was seaching for a long time and finally i wrote the function that working well. But one problem.. I can't kill it on click.)) I set lots of variants but in every case when i click on "stop" button function still working. Can you point me on mistake. Maybe i set setInterval incorrect? Thank you. DEMO <button>Stop</button> <div> <div class="pics"> <p>1</p> </div> <div class="pics"> <p>2</p> </div> <div class="pics"> <p>3</p> </div> <div class="pics"> <p>4</p> </div> </div> .pics { position:absolute; display:none; } .pics p { font-size:20px; color:green; } var timer; function fade($ele) { $ele.fadeIn(2000).delay(3000).fadeOut(2000, function() { var $next = $(this).next(); fade($next.length > 0 ? $next : $(this).parent().find($('.pics:first'))); }); }; timer=setInterval(fade($('.pics:first')), 500); $("button").click(function(event) { event.preventDefault(); clearInterval(timer); });
November 3, 201411 yr setInterval expects a function. Try re-writing part of your code to this: timer=setInterval(function () { fade($('.pics:first')); }, 500);
November 3, 201411 yr Author Skateside, thank you for answer! I tried, but it not working. When i changed position (in my layout i have no position, relative by default) i got error. And button "Stop" still not working. I created new Demo with your correction DEMO
November 3, 201411 yr Not sure why you're using setInterval. Your fade() function is already in a loop.You just need to stop the animation when your button is clicked. function fade($ele) { $ele.fadeIn(2000).delay(3000).fadeOut(2000, function () { var $next = $(this).next(); fade($next.length > 0 ? $next : $(this).parent().find($('.pics:first'))); }); }; fade($('.pics:first')); $("button").click(function (event) { $('.pics').stop(true); }); http://jsfiddle.net/1s4u2kxe/
November 3, 201411 yr Author Wynn, thank you very much for answer! Its working perfect! I know that function is already in loop, but i didn't know another way to stop the function, that's why i set setInterval. I am stuped)) Thank you for help, i have lots of similar deal in work and now i know how i should act to solve this problem.
November 5, 201411 yr Author Today i tried to set one extra option to my slider. I want to restart animation loop on mouseleave (when i leave the div's wrapper), but i got an error again. Can you give me advice is it possible to set mouseleave function on parent element and where i can make mistake in this code? Thank you! DEMO
Create an account or sign in to comment