gazelle
gazelle

Reputation: 135

Looping through JSON object and only getting last record

My goal is to have a list of quotes in a JSON file and rotate through them. Everything looks good and the javascript is running the right amount of times and actually fading in and out like expected but somehow it's only displaying the last key of the array.

Simple html:

<div class="testimonial__content"></div>

Javascript:

var testimonials = [{
    "quote" : "Always remember that you are absolutely unique. Just like everyone else.",
    "image": "http://placekitten.com/g/50/50"
},
{
    "quote" : "People who think they know everything are a great annoyance to those of us who do.",
    "image": "http://placekitten.com/g/50/50"
}
];

var currentQuote = $(".testimonial__content");

for (var key in testimonials) {    
    var myHtml = testimonials[key].quote;
    changeHtml (myHtml);
}

function changeHtml(myhtml){
    currentQuote
    .fadeIn(2000)
    .delay(2000)
    .text(myhtml)
    .fadeOut(2000);
}

Fiddle: http://jsfiddle.net/janL3r6v/

I think I can try different things to make it work but I just don't understand why it's running the right amount of times but it's getting only the last array. Also, debugging myHtml shows all the quotes.

Upvotes: 1

Views: 383

Answers (1)

Barmar
Barmar

Reputation: 781120

You have to wait until the previous animation is complete before starting the next one. You can do this by starting the next animation in the callback function of the fadeOut:

var testimonials = [{
  "quote": "Always remember that you are absolutely unique. Just like everyone else.",
  "image": "http://placekitten.com/g/50/50"
}, {
  "quote": "People who think they know everything are a great annoyance to those of us who do.",
  "image": "http://placekitten.com/g/50/50"
}];

var currentQuote = $(".testimonial__content");
var quoteIndex = 0;

function changeHtml() {
  var myHtml = testimonials[quoteIndex].quote;
  quoteIndex = (quoteIndex + 1) % testimonials.length;
  currentQuote
    .fadeIn(2000)
    .delay(2000)
    .text(myHtml)
    .fadeOut(2000, changeHtml);
}
$(document).ready(function() {
  changeHtml(); // Start the cycle
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="testimonial__content"></div>

Upvotes: 2

Related Questions