I’m adding a class on hover to various links, works great. However, when you click on the link, sometimes the new added class stays or the JS becomes unstable. I’m guessing I need to add a remove class onclick?
$("a").hover(function () {
switch ($(this).attr("href")) {
case "somelink1.html":
parent.top.$(".start-box").toggleClass("tutorialHover");
break;
case "somelink2.html":
parent.top.$(".end-box").toggleClass("tutorialHover");
break;
// etc..
I don’t see the full code here (truncated by an etc) but hover expects two functions. It’s just an encapsulation of
mouseenterandmouseleavein one. You just need to addClass in the enter part and removeClass in the exit part. The click shouldn’t have anything to do with it unless you do indeed expect something different if you’re still hovering and yet have also clicked.Toggling class is better for single events like click. Hover always has at least the potential to always trigger the in and also the out (unless you just never move your mouse!) so be explicit about when the class should be added and when it should be removed.
http://jsfiddle.net/As2dF/
D’oh, just realized you can set the same event for both in and out… I’ll leave my answer anyhow since I do feel it’s better to be explicit: two functions—one in and one out—but I’m wrong that you NEED to supply two.
[update]
Experimenting with it as one function doing double-duty (ie.
toggleClassin the one function instead ofaddClassandremoveClassand unsurprisingly it’s impossible to reproduce the click problem. This leads me to believe that it’s either:Noticed that you’re not preventing default behaviour on the links. A plausible guess is that you’re hovering (adding class), clicking (refreshing page) and your mouse is still in position over the NON-CLASSED element; when you move out, class is then toggled. If it’s this problem or even something related, this is how being explicity about
addClassandremoveClass(instead oftoggleClass) ensures it’s doing what you want it to do. That said, if this IS the problem, you can update the beginning of your function to look like this so that thehrefdoesn’t get triggered.selector error (you are adding and removing from two different “levels” that happen to overlap, causing classes to get super wonky
related to #1, an event bubbling error. Although you may not ultimately want to stop propagation altogether, see if this experiment works– for your trigger function, pass the event and stop propagation on it:
This may cause other unwanted side-effects (maybe other events aren’t being triggered that need to be!) but at least it will help isolate bubbling issues.