loop ticker

by uto usui

HTML

<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/bulma/0.5.3/css/bulma.min.css">
<section class="hero is-medium is-primary is-bold">
  <div class="hero-body">
  <div class="container">
    <div class="ticker" id="js-ticker">
      <ul class="title">
        <li class="js-item"><a href=""><strong>【緊急告知】</strong>勝利の理由 独占放送決定!</a></li>
        <li class="js-item"><a href=""><strong>【キャンペーン】</strong>TV Everywhere キャンペーン</a></li>
        <li class="js-item"><a href=""><strong>【キャンペーン】</strong>TV Everywhere キャンペーン</a></li>
      </ul>
    </div>
  </div>
  </div>
</section>

SCSS

.ticker {
  line-height: 1;
  //
  > ul {
    padding-top: .5rem;
    padding-bottom: .5rem;
    white-space: nowrap;
    //
    > li {
      display: inline-block;
      white-space: nowrap;
      //
      + li {
        margin-left: 30px;
      }
    }
  }
}

JavaScript

const ticker = (target, margin = 0) => {

  let $target = $(target),
      $inner = $target.children(),
      containerWidth = 0,
      left = 0,
      width = 0;

  const size = () => {

    containerWidth = $target.width();
    left = containerWidth;

    $target.find('.js-item').each(function() {

      width = width + $(this).outerWidth() + margin;

    });

  };
  size();

  let tick = () => {

    if (--left < -width) {

      left = containerWidth;

    }

    $inner.css({
      'transform': 'translateX(' + left + 'px)'
    });

    setTimeout(tick, 16);

  };

  tick();

};
ticker('#js-ticker', 30);