I have a div in CSS that works like this: SomeDiv has another class, that’s sometimes SomeRedDiv and other times SomeBlueDiv. When I mouseenter on SomeDiv, I want it to add the class SomeYellowDiv. But when I mouseleave, I want it each div to return to its initial state, either SomeRedDiv or SomeBlueDiv. This is what I have:
<div class="SomeDiv SomeRedDiv"></div>
<div class="SomeDiv SomeBlueDiv"></div>
$('.SomeDiv').mouseenter(function () {
// this makes all SomeDivs turn yellow
$(this).removeClass().addClass('SomeDiv SomeYellowDiv');
});
$('.SomeDiv').mouseleave(function () {
// here I want to use closure so that the function remembers
// which class it initially was; SomeBlueDiv or SomeRedDiv
$('this).removeClass().addClass('SomeDiv'); // add the initial color class
});
I could do this with a global but I want to see if a closure would make my code better; I know the concept of closure that allows functions to remember their state but I’m not sure how to make it work here.
Thanks for your suggestions.
Clsoures don’t apply here, since you have two unrelated functions.
Instead, you should use
$(this).data(...), which stores arbitrary data associated with an element.