Razvan Cuceu Razvan Cuceu - 15 days ago 4
CSS Question

One side text ticker

I've made a text ticker using HTML/CSS/JS but after some minutes the text change gets desynchronized with the animation, the text is starting to change when it's visible. How can I improve the code so that it's changing only when it's hidden?



var arr = ["text1", "text2", "text3", "text4"];

(function headerMessage(counter) {
var text = arr[counter];
$('.header-message > span').text(text).animate({
'margin-left': '0px'
}, 500).delay("3000").animate({
'margin-left': '-300px'
}, 500);
delete arr[counter];
arr.push(text);
setTimeout(function() {
headerMessage(counter + 1);
}, 4000);
})(0);

.header-message {
border-left: 1px solid #e3e3e3;
padding-left: 10px;
line-height: 58px;
vertical-align: middle;
float: left;
margin-left: 10px;
overflow: hidden;
}
.header-message span {
font-family: Raleway;
font-size: 14px;
color: #979797;
font-weight: 500;
height: 30px;
line-height: 30px;
margin-left: -300px;
vertical-align: middle
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="header-message">
<span style="margin-left: 0px;">We love to help businesses like yours.</span>
</div>





Jsfiddle here https://jsfiddle.net/qhtbsh2L/

Answer

You shouldn't use a separate setInterval. Try queuing the change text action into your animations chain.

  var arr = ["text1", "text2", "text3", "text4"];

  (function headerMessage(counter) {
    var text = arr[counter];
    $('.header-message > span').text(text).animate({
      'margin-left': '0px'
    }, 500).delay("3000").animate({
      'margin-left': '-300px'
    }, 500).queue(function(next) {
      headerMessage(counter + 1);
      next();
    });
    delete arr[counter];
    arr.push(text);
  })(0);
.header-message {
  border-left: 1px solid #e3e3e3;
  padding-left: 10px;
  line-height: 58px;
  vertical-align: middle;
  float: left;
  margin-left: 10px;
  overflow: hidden;
}
.header-message span {
  font-family: Raleway;
  font-size: 14px;
  color: #979797;
  font-weight: 500;
  height: 30px;
  line-height: 30px;
  margin-left: -300px;
  vertical-align: middle
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="header-message">
  <span style="margin-left: 0px;">We love to help businesses like yours.</span>
</div>