user3576711
user3576711

Reputation: 45

Fading and changing elements

So I have this code: http://jsfiddle.net/N8drz/2/

The problem is that the code below needs to be multi-purposed so I can use it in other places on my site. So I need some abstraction help.

function change(){
    var showTime = 10000; // time before fade
    var fadeOutDuration = 300;
    var fadeInDuration = 500;
    var textIncrementer = 2;
    AnimateText();

    function AnimateText() {

        setTimeout(function() {
            jQuery("#contactHere").fadeTo(fadeOutDuration, 0, function() {
                if (textIncrementer == 1) {
                    displayText = "Text1";
                }
                if (textIncrementer == 2) {
                    displayText = "Text2";
                }    
                if (textIncrementer == 3) {
                    displayText = "Text3";
                    textIncrementer = 0;
                }
                textIncrementer++;
                jQuery("#contactHere").html(displayText);
                jQuery("#contactHere").fadeTo(fadeInDuration, 1, function(){
                    AnimateText();
                });

            });
        }, showTime);
    }
}

This is good for changing a text element and works perfectly, However if I wanted to have two elements, It would cycle through them in the same way it does with the text (hiding the element, fading it in, Hiding, fading in the next one...), What would be the easiest way to do this? If needed I could use php.

Thanks in advance!

Upvotes: 0

Views: 47

Answers (1)

Matt Burland
Matt Burland

Reputation: 45135

There are several ways to approach this, but here's one quick solution:

var showTime = 2000; // time before fade
var fadeOutDuration = 300;
var fadeInDuration = 500;

StartAnimation($("#contactHere"), [$("#info1"),$("#info2")]);


function StartAnimation(elem, set) {
    var textIncrementer = 0;
    AnimateText(elem, set);

    function AnimateText(elem, set) {
        setTimeout(function () {
            elem.fadeTo(fadeOutDuration, 0, function () {
                var displayText = set[textIncrementer].html();
                textIncrementer = (textIncrementer + 1) % set.length;         
                console.log(elem);
                elem.html(displayText);
                elem.fadeTo(fadeInDuration, 1, function () {
                    AnimateText(elem, set);
                });
            });
        }, showTime);
    }
}

I wrapped your AnimateText inside another function so that the index textIncrementer is kept private and cannot be accidently overwritten. I also stripped out the if...else logic and instead passed in an array of elements and used indexing to pick the correct one.

Here's a fiddle

I also just copied the html from the target divs. It might back more sense to .detach and .append the elements themselves.

Upvotes: 1

Related Questions