javascriptjquerymouseovertickernews-ticker

Pause Jquery script on mouseover


I use this little code snippet for a jquery news ticker:

var speed = 5;
var items, scroller = $('#scroller');
var width = 0;

scroller.children().each(function(){
    width += $(this).outerWidth(true);
});

scroller.css('width', width);

scroll();

function scroll(){
    items = scroller.children();
    var scrollWidth = items.eq(0).outerWidth();
    scroller.animate({'left' : 0 - scrollWidth}, scrollWidth * 100 / speed, 'linear', changeFirst);
}

function changeFirst(){
    scroller.append(items.eq(0).remove()).css('left', 0);
    scroll();
}

I try to pause the script when mouseover.

Using stop() function, it works but it loses speed every time I pass my mouse over.

I know their is something to do with width / distance / speed but I'm unable to correct it.

Here is the full script: http://codepen.io/anon/pen/wBayyz

Thank You.


Solution

  • $(document).ready(function(){
      
        var speed = 5;
        var items, scroller = $('#scroller');
        var width = 0;
      
        scroller.children().each(function(){
            width += $(this).outerWidth(true);
        });
      
        scroller.css('width', width);
      
        scroll();
        
        function scroll(){
            items = scroller.children();
            var scrollWidth = items.eq(0).outerWidth();
            scroller.animate({'left' : (items.eq(0).offset().left - 39) - scrollWidth}, scrollWidth * 100 / speed, 'linear', changeFirst);
        }
      
        function changeFirst(){
            scroller.append(items.eq(0).remove()).css('left', 0);
            scroll();
        }
      $("#scroller").hover(function() {
      $(this).stop();
    }, function() {scroll();});
    });
    #scroller{height:100%;margin:0;padding:0;line-height:30px;position:relative;}
    
    #scroller li{float:left;height:30px;padding:0 0 0 10px;list-style-position:inside;}
    
    #scrollerWrapper{width: 500px; height:30px;margin:30px;overflow:hidden;border:1px #333 solid;background:#F2F2F2;}
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
    <html>
    <head>
    <title>Horizontal scroller</title>
    </head>
    <body>
      
    <div id="scrollerWrapper">
      
      <ul id="scroller">
    
        <li>Lorem ipsum dolor sit amet, consectetur adipiscing elit.</li>
    
        <li> Maecenas sollicitudin, ante id ultrices consectetur.</li>
    
        <li>Cum sociis natoque penatibus et magnis dis parturient. </li>
    
      </ul>
      
    </div>
    </body>
    </html>

    The problem was when you were restarting the scrolling you need to take into consideration how much has been scrolled already, like I've done here.

    This should be what you're looking for,