News Ticker

Basic news marquee using JS

by mrjordy

HTML

<div id="news-ticker">
    <div class="ticker-title">Breaking News: </div>
    <ul>
        <li>
            <a href="http://www.thetimes.co.uk/tto/news/uk/crime/article3999682.ece">No 10 armed police arrested over hardcore pornography</a>
        </li>
        <li>
            <a href="http://www.thetimes.co.uk/tto/environment/article3999530.ece">EDF extends life of UK nuclear plants</a>
        </li>
    </ul>
</div>

CSS

#news-ticker { 
    font-weight: bold;
    display: block;
    font-family: monospace;
    font-size: 15px;
    padding: 0;
    margin: 0
}

#news-ticker .ticker-title {
    display: inline-block;
    margin-right: 32px;
}

#news-ticker ul { 
    display: inline-block;
    position: relative;
}

#news-ticker li a {
    color: #f00;
    text-decoration: none;
}

#news-ticker li a:hover {
    text-decoration: underline;
    color: #00f;
}

#news-ticker li {
    position: absolute;
    left: 0;
    width: 0;
    overflow: hidden;
    height: auto;
    word-wrap: break-word;  
    opacity: 0
}

#news-ticker li.tick {
    -webkit-animation: tick 5s linear;
    
}

@-webkit-keyframes tick {
  0% {
    width: 0;
  }
  5% {
      opacity: 1;
  } 
  90% {
    width: 550px;
    opacity: 1;
  }
  100% {
     opacity: 0
  }
}

JavaScript

$(function () {
    var $ticker = $('#news-ticker'),
      $first = $('li:first-child', $ticker);
    
    // put an empty space between each letter so we can 
    // use break word
    $('a', $ticker).each(function () {
        var $this = $(this),
          text = $this.text();
       $this.html(text.split('').join('&#8203;'));
    });
    
    // begin the animation
    function tick($el) {
        $el.addClass('tick')
          .one('webkitAnimationEnd oanimationend msAnimationEnd animationend', function () {
              
            $el.removeClass('tick');
              var $next = $el.next('li');
              $next = $next.length > 0 ? $next : $first;
            tick($next);
        });
    }
        
    tick($first);
    
});