-1

This question has been asked many times, but as a beginner, it's hard for me to apply other peoples scripts to my own assigned classes and vars.

What I would like to know is:

I have a simple area in the html that looks like this:

<h1>I like: <span class ="hobbies">array items go here</span></h1>

I've made an array as such:

var hobbies=new Array("graphic design.","photography.", "videography.", "marketing.", "craft beers.")

I want each item to appear by itself for say 3 seconds or so then fade out and get replaced by the next item in the array. I would also like for this to loop once it has finished going through all the options. How could I do something like this?

I also have:

$('.hobbies').html(hobbies);

Thanks in advance for reading through!

asked Apr 30, 2013 at 16:24
1

2 Answers 2

3

Basically you're going to have to use a setInterval to repeat the function at specific time delays.

Save an index of the current position in the hobbies array and on each iteration increase the index. Make sure to reset the index when it reaches the same value as your arrays length.

// Always a good idea to cache selectors you're gonna be using alot.
var hobbyContainer = $('.hobby');
hobbyContainer.text(hobbies[0]);
var index = 1;
setInterval(function(){
 hobbyContainer.fadeOut('fast',function(){
 hobbyContainer.text(hobbies[index]);
 index++;
 if (index >= hobbies.length){
 index = 0;
 }
 }).fadeIn('fast');
},3000); 

You might have to play with the duration of the interval in order to leave time for the fading animation. Or you could make the fade animation faster as I have done in my example.

Here is a simple demo on jsFiddle

answered Apr 30, 2013 at 16:28
Sign up to request clarification or add additional context in comments.

1 Comment

I think it should be index >= hobbies.length or index == hobbies.length
-1

Try something like this -

 var hobbies = //"yourarray";
 var count = 0;
 setInterval(function() {
 scrollText(hobbies[count]);
 count++;
 if (count == hobbies.length ) {
 count = 0;
 }
 }, 3000);
function scrollText(text) { 
 $(".hobbies").animate({opacity:0},function(){
 $(this).html(text).animate({opacity:1}); 
 });
}

Working Demo

answered Apr 30, 2013 at 16:32

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

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.