I am using CSS Image sprites for roll over effect on a element, the new class to be applied on mouse over is assigned to attribute data-toggle-class and below is the code ( I now this is miniature performance improvement and doing pre-optimization which is not good)
$("*[data-toggle-class]").hover(function(ev){
var a = $(this);
a.toggleClass(a.attr("data-toggle-class"))
});
- how do I cache
data-toggle-classattribute rather than retrieving it every time the hover occurs. - Even though I use Image sprite there is small lag before the switch effect happens. Is this known issue
I can only answer the question about caching (mostly, see note under the divider below), which you can do with a closure:
What that does is, instead of having a single function that gets called for all of the matching elements during hover events, it generates a separate function for each element, where the function closes over a reference to a jQuery wrapper for the element and a copy of its
data-toggle-classattribute. It trades off size (more functions = more memory, though you’d have to have a lot of these for it to start to matter) for speed.If your goal is to have the class on hover and not have it when not hovering, I’d probably do that explicitly:
You’ve said
…but I’d just like to underscore that. The above will work, probably won’t cause excessive memory use, and will result in a tiny performance enhancement, but I tend to think that enhancement will be below the threshold of human perception.
I wonder if you really need the class, and the JavaScript code, at all? Unless you need to support IE6, the
:hoverCSS pseudo-class is exactly for this purpose, and is handled natively by the browser rather than by JavaScript code (read: faster). For instance:…will make any element with a
data-toggle-classattribute green normally, but blue when hovered. If you need to do different things based on the value of the attribute, you can do that:Elements with
data-toggle-class="foo"will be green normally, blue when hovered; ones withdata-toggle-class="bar"will be black normally, and red when hovered. No JavaScript required.In the above you understand
coloris just an example; I expect you’re usingbackgroundandbackground-positionif you’re using sprites.Here’s a proper example of the CSS technique (live copy | source):
CSS:
HTML:
Note how you can readily control which arrow appears, declaratively, with no JavaScript. Now, of course, if your conditions for which arrow should appear are more complicated than that, you may well have to go to JS. I’m just saying, for most simple hover ops, it’s not needed.