How to make this JavaScript much faster?
- by Ralph
Still trying to answer this question, and I think I finally found a solution, but it runs too slow.
var $div = $('<div>')
.css({ 'border': '1px solid red', 'position': 'absolute', 'z-index': '65535' })
.appendTo('body');
$('body *').live('mousemove', function(e) {
var topElement = null;
$('body *').each(function() {
if(this == $div[0]) return true;
var $elem = $(this);
var pos = $elem.offset();
var width = $elem.width();
var height = $elem.height();
if(e.pageX > pos.left && e.pageY > pos.top
&& e.pageX < (pos.left + width) && e.pageY < (pos.top + height)) {
var zIndex = document.defaultView.getComputedStyle(this, null).getPropertyValue('z-index');
if(zIndex == 'auto') zIndex = $elem.parents().length;
if(topElement == null || zIndex > topElement.zIndex) {
topElement = {
'node': $elem,
'zIndex': zIndex
};
}
}
});
if(topElement != null ) {
var $elem = topElement.node;
$div.offset($elem.offset()).width($elem.width()).height($elem.height());
}
});
It basically loops through all the elements on the page and finds the top-most element beneath the cursor.
Is there maybe some way I could use a quad-tree or something and segment the page so the loop runs faster?