Search code examples
jquerycssjquery-effects

How implement text-carousel for large text in small spaces with jQuery?


I would like a long text to be displayed dynamically in a div with small width. I have seen this effect on some mobile phones:

First part of large text

Next parts of large text

When it show last part of text, the carousel effect change of direction and start again.

I can´t find any plugin or example related to this.

How can I implement it with jQuery?


Solution

  • I'm not sure if such a library exists, but I've just created an implementation of this using only jQuery based on your question.

    Let me know if you have any questions about how it works, and hope this helps!

    // adjust these:
    var loopScrollSpeed = 5;    // adjust speed (lower = slower)
    var loopPauseLength = 1000; // pause in miliseconds
    var loopSelector = '.loop-text';
    
    // create our function:
    function loopText(el, widthDiff, starting) {
      el.animate({
        'left': starting ? -widthDiff : 0
      }, widthDiff * 100 / loopScrollSpeed, 'linear', function() {
        setTimeout(function() {
          loopText(el, widthDiff, !starting);
        }, loopPauseLength);
      });
    }
    
    // loop through all elements with our selector
    $(loopSelector).each(function() {
      el = $(this).find('span');
      widthDiff = el.width() - $(this).width();
      if (widthDiff > 0) {
        loopText(el, widthDiff, true);
      }
    });
    .loop-text {
      /* adjust these: */
      border: 1px solid blue;
      width: 150px;
    
      /* leave these: */
      overflow: hidden;
      position: relative;
      text-align: center;
    }
    
    .loop-text span {
      white-space: nowrap;
      position: relative;
    }
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    
    <div class="loop-text">
      <span>The Beatles &mdash; A Day in the Life</span>
    </div>
    
    <br>
    
    <div class="loop-text">
      <span>Text fits - no scroll</span>
    </div>
    
    <br>
    
    <div class="loop-text">
      <span>Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.</span>
    </div>