Reputation: 23
i have this code: http://jsfiddle.net/VCorreia44/G4Kjr/ My problem is when I click the first button starts the fadeIn fadeOut effect, but when I click the second the effect don't stop immediately.Thanks for your help in advance.
<dt id="t1">Hello World</dt>
<button type="submit" onclick="myFunction()">...</button>
<button type="submit" onclick="Pause()">...</button>
var data_val1 = 1;
var timer;
function myFunction() {
if (data_val1 < 1) {
document.getElementById("t1").style.color = "#000000";
} else {
document.getElementById("t1").style.color = "#FF0000";
$("#t1").fadeOut("slow").fadeIn("slow");
timer = setTimeout('myFunction()', 1000);
}
};
function Pause() {
clearTimeout(timer);
}
Upvotes: 2
Views: 73
Reputation: 36794
There is no need for setTimeout()
- don't chain your fade functions, use callbacks. Also, since your using jQuery, you might as well be consistent and take advantage of css()
:
function myFunction() {
if (data_val1 < 1) {
$("#t1").css({color:'#000'});
} else {
$("#t1").css({color:'#F00'}).fadeOut("slow", function(){
$(this).fadeIn("slow", myFunction);
});
}
};
And to stop the fading:
function Pause() {
$("#t1").stop();
};
Upvotes: 3
Reputation: 10127
Here is my approach to the problem:
HTML:
<dt id="t1">Hello World</dt>
<button class="anim-start">Start</button>
<button class="anim-stop">Stop</button>
jQuery:
function animate(){
$("#t1").fadeOut('slow').fadeIn('slow', animate);
}
$(".anim-start").on("click", function(){
$("#t1").css("color", "red");
animate();
});
$(".anim-stop").on("click", function(){
$("#t1").css("color", "").css("opacity", 1).stop(true);
});
Clean and working!
Upvotes: 0
Reputation: 13829
You need to add something like this to the Pause
function:
$("#t1").stop();
$("#t1").css({opacity:1});
otherwise the animation will continue until the animation reaches full opacity. If you just want to stop it in it's current position, you could just $("#t1").stop();
Also, you're using jQuery, so you should change document.getElementById("t1").style.color
to $("$t1").css({color:someColor});
Read more about jQuery's .stop()
Upvotes: 1