morgi
morgi

Reputation: 1025

jQuery animate on click multiple times

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:

  1. The random class is added
  2. The div pops up from the bottom of the page with its opacity increasing

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

Answers (3)

George
George

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);
});

JSFiddle

Documentation:

Upvotes: 2

Balachandran
Balachandran

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(){


        });
    });

DEMO

Upvotes: 1

byJeevan
byJeevan

Reputation: 3838

Re initialize the margin-top of #content to 200px after animation :

     $("#content").css("margin-top","200px");

DEMO HERE

Upvotes: 0

Related Questions