Reputation: 53
I have 4 DIV
that I want to have a scroll
event fired when you scroll on one of those div's. This is the code below.
$('#div1, #div2, #div3, #div4').scroll(function() {
alert('...');
});
In Firefox/Chrome, this runs fast; however, in Internet Explorer this runs so slow that it actually prevents me from scrolling the div.
I'm using the latest version of JQuery (v.1.4.1).
UPDATE: Since it was asked, I've included below my entire code:
$('#div1, #div2, #div3, #div4').scroll(function() {
/* find the closest (hlisting) home listing to the middle of the scrollwindow */
var scrollElemPos = activeHomeDiv.offset();
var newHighlightDiv = $(document.elementFromPoint(
scrollElemPos.left + activeHomeDiv.width() / 2,
scrollElemPos.top + activeHomeDiv.height() / 2)
).closest('.hlisting');
if(newHighlightDiv.is(".HighlightRow")) return;
$('.HighlightRow').removeClass("HighlightRow");
newHighlightDiv.addClass('HighlightRow');
/* change the map marker icon to denote the currently focused on home */
var activeHomeID = newHighlightDiv.attr("id");
if (activeHomeMarkerID) {
// unset the old active house marker to a normal icon
map.markers[activeHomeMarkerID].setIcon('http://example.com/images/house-icon.png');
}
activeHomeMarkerID = activeHomeID.substring(4); // set the new active marker id
map.markers[activeHomeMarkerID].setIcon('http://example.com/images/house-icon-active.png');
});
UPDATE 2:
So I've implemented the timer option below and in IE, it's still just as slow. Any other ideas?
Upvotes: 3
Views: 7729
Reputation: 23803
In IE, the scroll event is dispatched way more often than in Firefox. You are doing many DOM operations in the event handler that makes it run slower.
Consider doing all this stuff when the user stops or momentarily pauses scrolling. Here's an article on how this technique can be implemented - http://ajaxian.com/archives/delaying-javascript-execution
Edit: Here's an implementation
var timer = 0,
delay = 50; //you can tweak this value
var handler = function() {
timer = 0;
//all the stuff in your current scroll function
}
$('#div1, #div2, #div3, #div4').scroll(function() {
if (timer) {
clearTimeout(timer);
timer = 0;
}
timer = setTimeout(handler, delay);
});
Edit 2: Can you attach a profiler (like the IE8 profiler) and see what's running slow? How complex is your DOM?
Here are some ideas for improving performance of your code:
activeHomeDiv.offset()
each time? Can you measure it once and store it somewhere (if the position doesn't change)? Measuring size causes a browser repaint.newHighlightDiv.is(".HighlightRow")
to newHighlightDiv.hasClass("HighlightRow")
$('.HighlightRow').removeClass("HighlightRow")
- Add an element prefix and descend from an id selector/element reference, such as $('div.HighlightRow', '#ancestorDiv')
. Upvotes: 6