Reputation: 460
My question is driven by curiosity, and I appreciate any performance difference is liable to be minuscule.
I was recently looking at producing some hover effects for an image map. As with most things someone else had suggested a method with jQuery. Below was the suggest code
$('#borders area').each(function(){
var mapRegion = $(this).attr('class');
$(this).hover(
function(){
$('#regions').addClass(mapRegion).show();
},
function(){
$('#regions').hide().removeClass(mapRegion);
});
});
This obviously works fine where <div id="regions">
is positioned absolutely above a base <img>
and the a further blank transparent <img>
is placed above this for <map id="borders">
.
I did wonder however if it made more sense (slightly less code) to do the following with the jQuery
$('#borders area').each(function(){
$(this).hover(
function(){
$('#regions').removeClass().addClass($(this).attr('class')).show();
},
function(){
$('#regions').hide();
});
});
Would this be faster as no variable is set? Does removeClass() work faster without a parameter supplied? I suppose I would also be interested to know which semantically is considered better.
Upvotes: 1
Views: 107
Reputation: 342635
Would this be faster as no variable is set? Does removeClass() work faster without a parameter supplied?
Since you are concerned with knowing what the difference in performance is from an academic perspective (since there will probably never, ever be a perceptible one), I would suggest doing some benchmarking of your own.
A useful online tool for that: http://jsperf.com/
Upvotes: 1
Reputation: 318182
In my opinion what would make more sense is probably :
$('#borders area').on('mouseenter mouseleave', function(e) {
if (e.type == 'mouseenter') {
$('#regions').removeClass().addClass(this.className).show();
}else{
$('#regions').hide();
}
});
As that avoids the uneccessary loop and hover()
wrapping of mouseenter/mouseleave, and gets the classname from the native property.
As for speed, you'll never notice the difference.
Upvotes: 1