Hansal Mehta
Hansal Mehta

Reputation: 195

How to animate the HTML contents using jquery..

I have an HTMl texts that is getting changed dynamically.Now as per my requirement i have to display them in animated form like fading and in some motion but i am not aware of this .. Here is my Code..

<script type="text/javascript">
        var v = {};
        v[0] = "Your Text<br/>Hello";
        v[1] = "Your Text2<br/>Hello2";
        v[2] = "Your Text3<br/>Hello3";

        var i = 0;

        window.setInterval(function () {
            $("#dynamicMessage").html(v[i]);
            if (i == 2) {
                i = 0;
            } else {
                i = i + 1;
            }

        }, 10000);
</script>

Please have a look and let me know how can i animate my text contents in HTML.. Thanks..

Upvotes: 0

Views: 76

Answers (4)

Alex
Alex

Reputation: 9031

You could use a combination of fadeOut() and fadeIn()

$("#dynamicMessage").fadeOut( "slow", function() {
    $("#dynamicMessage").html(v[i]).fadeIn('slow');
})

Check this demo - http://jsfiddle.net/xw2j6hsp/1/

UPDATE

Saw this comment, on @laruiss answer:

"If there are other way by which i can show the text popping from the left"

Thought i'd code this up for you. Just add in some animation. check it - http://jsfiddle.net/m6bnq1ja/

Upvotes: 3

Priyank
Priyank

Reputation: 3868

 var v = {};
    v[0] = "Your Text<br/>Hello";
    v[1] = "Your Text2<br/>Hello2";
    v[2] = "Your Text3<br/>Hello3";

        var i = 0;
        window.setInterval(function () {
        $("#dynamicMessage").fadeToggle( "slow", function() {
            $("#dynamicMessage").html(v[i]).fadeToggle('slow');
        });
        if (i == 2) {
            i = 0;
        } else {
            i = i + 1;
        }

    }, 4000);

Note : you can also use "fadeOut" & "fadeIn" in place of "fadeToggle"

Upvotes: 1

laruiss
laruiss

Reputation: 3816

Don't forget to clearTimeout (or clearInterval)

var v = [
        "Your Text<br/>Hello",
        "Your Text2<br/>Hello2",
        "Your Text3<br/>Hello3"
    ],
    i = 0,
    timeout = null,
    change = function (text) {
        var $dynamicMessage = $("#dynamicMessage")
            .fadeOut("slow", function() {
                $dynamicMessage.html(text).fadeIn();
            });
        if (i == 2) {
            i = 0;
        } else {
            i = i + 1;
        }
        timeout = window.setTimeout(function() {change(v[i]);}, 2000);
    }
change(v[i]);

$(window).unload(function() {window.clearTimeout(timeout); timeout = null;});

JSFiddle

Upvotes: 1

artm
artm

Reputation: 8584

There's no animating the content change. What you can do is hide the element, change its content, then fade it in, something like below. It'll probably look the same to the user.

$("#dynamicMessage").hide().html(v[i]).fadeIn();

or

 $("#dynamicMessage").fadeOut(500, function() {
    $(this).html(v[i]).fadeIn(500);
});

Upvotes: 1

Related Questions