I am currently thinking about some efficiency/speed issues.
I have about 40 a elements and divs nested in li´s
<ul id=ul>
<li><a href="#">Link</a><div>Text</div></li>
<li><a href="#">Link</a><div>Text</div></li>
<li><a href="#">Link</a><div>Text</div></li>
<li><a href="#">Link</a><div>Text</div></li>
<li><a href="#">Link</a><div>Text</div></li>
....
</ul>
On all the li´s I have hover events attached
$('#ul li').hover(function(e){
$(this).children(div).show();},
function(){
$(this).children(div).hide();
})
I was wondering if there was a better way than attaching 40 event handlers to the dom for a hover event. I think this can be slow in some browsers.
I heard about DOM traversing, like when you put only ONE handler on the #ul container and let dom traversing inside the browser (e.target) figure out what element has been hoverd. Anybody know how to approach this issue?
.delegate()does what you describe:Note that
.hover()is just a shortcut for the two events, mouseenter and mouseleave, hence the two calls to.degelate()above.Even though
.delegate()is called on$('#ul'),$(this)will refer to the<li>element inside the events handlers.