Search code examples
javascriptjqueryticker

I was trying to make a news ticker. But there's an error when mouse leaves after hover


After Mouse Leave the ticker starts to move at a very high speed. Don't know what's the error.

Javascript:

$('#tick2').html($('#tick').html());
var temp=0,intervalId=0;
$('#tick li').each(function() {
    var offset=$(this).offset();
    var offsetLeft=offset.left;
    $(this).css({'left':offsetLeft+temp});
    temp=$(this).width()+temp+10;
});
$('#tick').css({'width':temp+40, 'margin-left':'20px'});
temp=0;
$('#tick2 li').each(function(){
    var offset=$(this).offset();
    var offsetLeft=offset.left;
    $(this).css({'left':offsetLeft+temp});
    temp=$(this).width()+temp+10;
});
$('#tick2').css({'width':temp+40,'margin-left':temp+40});

function abc(a,b) {  
    $('#outer').mouseenter(function() { window.clearInterval(intervalId);intervalId=0; });
    $('#outer').mouseleave(function() { start(); })
    var marginLefta=(parseInt($("#"+a).css('marginLeft')));
    var marginLeftb=(parseInt($("#"+b).css('marginLeft')));
    if((-marginLefta<=$("#"+a).width())&&(-marginLefta<=$("#"+a).width())){
        $("#"+a).css({'margin-left':(marginLefta-1)+'px'});
    } else {
        $("#"+a).css({'margin-left':temp});
    }
    if((-marginLeftb<=$("#"+b).width())){
        $("#"+b).css({'margin-left':(marginLeftb-1)+'px'});
    } else {
        $("#"+b).css({'margin-left':temp});
    }
} 

function start() { intervalId = window.setInterval(function() { abc('tick','tick2'); }, 10) }

start();

You can check the working demo here : http://jsfiddle.net/mstoic/juJK2/


Solution

  • Well, you nearly blew up my browser! Can you try this instead:

     function abc(a,b) {  
    
    var marginLefta=(parseInt($("#"+a).css('marginLeft')));
    var marginLeftb=(parseInt($("#"+b).css('marginLeft')));
    if((-marginLefta<=$("#"+a).width())&&(-marginLefta<=$("#"+a).width())){
        $("#"+a).css({'margin-left':(marginLefta-1)+'px'});
    } else {
        $("#"+a).css({'margin-left':temp});
    }
    if((-marginLeftb<=$("#"+b).width())){
        $("#"+b).css({'margin-left':(marginLeftb-1)+'px'});
    } else {
        $("#"+b).css({'margin-left':temp});
    }
    } 
    
     function start() { intervalId = window.setInterval(function() { abc('tick','tick2'); }, 10) }
    
     $(function(){
          $('#outer').mouseenter(function() { window.clearInterval(intervalId); });
          $('#outer').mouseleave(function() { start(); })
          start();
     });
    

    Working fiddle: http://jsfiddle.net/juJK2/1/

    You should only bind your event handlers once, not every time you enter abc();