Reputation: 1025
I am currently building a web app where I need to randomly generate text content and switch its color every time a button is clicked.
At the moment, I'm trying to add some kind of animation to it, and here's what I'd like to obtain each time the button is clicked:
I prepared a simplified JSFiddle to illustrate my point below.
Example
http://jsfiddle.net/cdacx0tn/11/
var color = ["blue", "purple", "green"];
$("#try-me").click(function() {
var colorClass = color[Math.floor(Math.random()*color.length)];
$("#content")
.removeClass()
.addClass(colorClass)
.animate({
"margin-top": "50px",
"opacity": "1"
}, 700);
});
I managed to get this done when the button is clicked once but I can't figure out how to do this each time it is clicked.
I want to add that I'm not a professional developper so please be indulgent.
Thanks for your help.
Upvotes: 1
Views: 2008
Reputation: 36784
Set the CSS of the element before animating it, making sure it's back at it's initial position with marginTop
and can't be seen using opacity
.
Add a stop()
in their to prevent animations being queued and there you have it:
var color = ["blue", "purple", "green"];
$("#try-me").click(function() {
var colorClass = color[Math.floor(Math.random()*color.length)];
$("#content")
.css({opacity:0,marginTop:200})
.removeClass()
.addClass(colorClass)
.stop(true,false)
.animate({
"margin-top": "50px",
"opacity": "1"
}, 700);
});
Documentation:
Upvotes: 2
Reputation: 9637
try
var color = ["blue", "purple", "green"];
$("#try-me").click(function() {
var colorClass = color[Math.floor(Math.random()*color.length)];
$("#content").css({ "margin-top": "200px", "opacity": "0"}); // reset the margin and opacity value
$("#content")
.removeClass()
.addClass(colorClass)
.animate({
"margin-top": "50px",
"opacity": "1"
}, 700,function(){
});
});
Upvotes: 1