开发者

jQuery slider - unexpected behaviour

I wrote small 'News Ticker'. I should make a loop through the spans, making fadeIn/fadeOut every 5s.

While untouched it is working fine, but when you try do play with the arrows(play forward arrow 5 times for example), script goes mad making fadeIn/fadeOut constatly.

Live example here.

Script:

        (function($) {

        $.fn.NoticeBoard = function() {


            // Set a timeout
            var timeOut = setTimeout(nextNotice, 5000);

            // pause on hover
            $('.noticeboard').hover(

            function() {
                clearTimeout(timeOut);
            }, function() {
                timeOut = setTimeout(nextNotice, 5000);
            });

            // Next notice function called on timeout or click

            function nextNotice(event) {
                clearTimeout(timeOut);
                timeOut = se开发者_如何学编程tTimeout(nextNotice, 5000);

                if ($('.noticeboard span:visible').is('.noticeboard span:last-child')) {
                    $('.noticeboard span:visible').fadeOut(300);
                    $('.noticeboard span:first-child').fadeIn();
                }
                else {
                    $('.noticeboard span:visible').fadeOut(300).next().fadeIn();
                }
                return false;
            }

            $('#notice-next').click(nextNotice);
            $('#notice-prev').click(function(event) {


                if ($('.noticeboard span:visible').is('.noticeboard span:first-child')) {
                    $('.noticeboard span:visible').fadeOut(300);
                    $('.noticeboard span:last-child').fadeIn();
                }
                else {
                    $('.noticeboard span:visible').fadeOut(300).prev().fadeIn();
                }
                return false;

            });

        };

    /*!  
    ---------------------------------------------*/

    })(jQuery);

    /*!  OnLoad
    ---------------------------------------------*/
    $(document).ready(function() {

        $('.noticeboard span').hide();
        $('.noticeboard span:first').show();
        $('.noticeboard').NoticeBoard();

    });

Any help with fixing the issue much appreciated.


I tried it here I declare a flag to carry the fadeIn is already done or not,so that we can never fire the event too much times...


I edited your code. You can see it live here. It is all about blocking flag which doesn't let you run the same code too many times. And I wrapped management of setTimeout and clearTimeout for better control I think.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜