0

I have this code, what am I trying to do is to make "fade-In fade-Out" effect off the text, while every time it will do fadeIn fadeOut its will replace the text (shown on p id="string") with the next array value but its show the last value every time (Name 3 - Message 3).

the html code below:

<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=utf-8" />
<script src="http://code.jquery.com/jquery-1.10.1.min.js"></script>
<script>
$(document).ready(function(){
    var str = $("#string").text().split(' + ');
    setInterval(function(){
        s++;
        for (var s = 0; s < str.length; s++) {
            var string = str[s];
            $("#string").html(string);
            $("#string").fadeIn(500);
            $("#string").fadeOut(3000);
        }   
    }, 6000);
});
</script>
</head>
<body>
<p id="string" style="display:none;">Name 1 - Message 1 + Name 2 - Message 2 + Name 3 - Message 3</p>
</body>
</html>

Thanks you.

0

2 Answers 2

1

You don't need any loop to achieve what you want:

var placeholder = $("#string");
var words = placeholder.text().split(' + ');
var index = 0;
window.setInterval(ShowCurrentWord, 6000);
ShowCurrentWord();
function ShowCurrentWord() {
    var currentWord = words[index];
    placeholder.html(currentWord).fadeIn(500).fadeOut(3000);
    index = (index + 1) % words.length;
}

Live test case.

Details: store the current index in a global variable then use that index and increment every execution of the function. Also note you need to call the function initially otherwise you'll wait 6 seconds before the first item appears.

Sign up to request clarification or add additional context in comments.

2 Comments

I love the index = (index + 1) % words.length
@mplungjan yeah, there are fancier ways but that's my prefered - elegant yet still readable enough. :)
0

Your code will display every time last item because you are doing the loop inside the timer.

You should replace your code with this:

$(document).ready(function(){

    var str = $("#string").text().split(' + ');
    var s = 0;
    var arrayLength = str.length;

    setInterval(function(){

        if(s>(arrayLength - 1)){
            s = 0;
        }   
        var string = str[s];
        $("#string").html(string);
        $("#string").fadeIn(500);
        $("#string").fadeOut(500);

        s++;

    }, 1000);
});

Here the fiddle: http://jsfiddle.net/zGSYz/

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.