I\'m working on a page with a fixed menu that picks up after the user has scrolled a certain distance from the top, and as they scroll down the page, different links from th
In addition to the other issues, $('body').scrollTop()
will always return 0 in Firefox. When setHash()
runs $('html,body').scrollTop(scrollmem);}
, it will jump to the top of the screen, which looks exactly like being stuck at the top of the screen when the user first loads the page. $(window).scrollTop()
, in conjunction with throttling, will solve this problem.
Basically you are executing too much in the scroll event. As @undefined said, the browser calls this a lot more than you might think. Some tips:
When inside a function that will be called many times, have your jQuery objects already created. That way, each time the function is called, it's not recreating the same jQuery object.
var nav2 = $("#nav_2");
$(window).scroll(function() {
...
nav2.removeClass('active');
...
});
Similarly, when called over and over again, adding and removing classes can consume a lot of your processing cycles - Especially when you are accessing a whole class of elements, like in $('.nav').addClass("f-nav");
.
Instead, try to add/remove the classes only if they don't exist. Something like:
var alreadyAdded = false;
var alreadyRemoved = false;
$(window).scroll(function () {
if ($(this).scrollTop() > 259) {
if(!alreadyAdded){
$('.nav').addClass("f-nav");
alreadyAdded = true;
alreadyRemoved = false;
}
} else if(!alreadyRemoved) {
$('.nav').removeClass("f-nav");
alreadyAdded = false;
alreadyRemoved = true;
}
});
All that said, it will still probably scroll slowly with all this code attached to the scroll event. Maybe there is another way you can get the same effect. If firefox is freezing, I can only imagine how slow this must be in IE.
Executing too much code on scroll event is overkill, on each scroll, browsers trigger the scroll event hundred times, you can consider using a library that have methods like throttle
or debounce
.
http://documentcloud.github.com/underscore/#throttle
It's a very, very, bad idea to attach handlers to the window scroll event. Depending upon the browser the scroll event can fire a lot and putting code in the scroll callback will slow down any attempts to scroll the page (not a good idea). Any performance degradation in the scroll handler(s) as a result will only compound the performance of scrolling overall. Instead it's much better to use some form of a timer to check every X milliseconds OR to attach a scroll event and only run your code after a delay (or even after a given number of executions - and then a delay). http://ejohn.org/blog/learning-from-twitter/