简体   繁体   中英

jQuery: when using the on .scroll event and alert firefox seems to infinite loop

I have the following jQuery code in one of my master templates:

$(document).scroll(function() {
    var scroll_top = $(document).scrollTop();
    alert(scroll_top);
    if (scroll_top <= 70) {
        $('#fixedback').fadeOut(500);
    } else {
        $('#fixedback').fadeIn(500);
    }
});

When the code executes Firefox 11 and 12 will blank the page and become unresponsive. I have to terminate the process in Task Manager. If I take out the alert(), the code executes perfectly. If I add an alert in any of the .scroll functions the same thing happens on any of my pages. The page will load and works until I scroll the page.

Using Jquery 1.7.1.min. and C# ASPX pages. I haven't tested on other browsers as it is only for development that I need the alerts to work.

It looks like a bug in Firefox.

The question: Firefox scrollTop problem has an answer that can be applied here. What it suggests is that you defer the alert() call using setTimeout() to give Firefox a chance to do whatever it needs to do to avoid blanking the page. Applying the workaround to your code, you would get something like this:

window.onscroll = catchScroll;
var timeOutId = 0;
var jitterBuffer = 200;
function catchScroll() {
    if (timeOutId) clearTimeout(timeOutId);
    timeOutId = setTimeout(function () { DoStuffOnScrollEvent() }, jitterBuffer);
}

function DoStuffOnScrollEvent() {
    var scroll_top = $(document).scrollTop();
    alert(scroll_top);
    if (scroll_top <= 70) {
        $('#fixedback').fadeOut(500);
    } else {
        $('#fixedback').fadeIn(500);
    }
};

Or, instead of alert() , you could use console.log() , which will work natively in later versions of IE and Chrome, and Firefox via Firebug .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM