Scriptaculous: Fixing Hover After Highlight

One of the annoying things about the highlight visual effect in Scriptaculous is that it will break your :hover background-color CSS definitions. The occurs because scriptaculous sets the background-color style property of the element to whatever it was set to before the effect began. This behavior would be desirable if you're using inline styles or setting the style property through javascript, but you will run into issues if you're doing it The Right Way™ and using CSS classes and Element.add/removeClassName. Fortunately, there is an easy solution to this problem.

To fix this on a case-by-case basis, you will need to use the afterFinish callback.

First, we'll define the function in some javascript so we can reuse it.

Object.extend(Effect.Highlight, {
  clearBackgroundStyle: function(effect) {
    effect.element.style.background = "";
  }
});

Unfortunately, we cannot use Element.setStyle to do this, as the blank style definition is ignored when going through prototype.

Now, we just need to set the callback. If you're in rails and doing RJS, it will look something like this:

page.visual_effect(:highlight, dom_id(@smurf),
  :afterFinish => 'Effect.Highlight.clearBackgroundStyle'
)

Which will produce the following javascript:

new Effect.Highlight("smurf_7",{
  afterFinish: Effect.Highlight.clearBackgroundStyle
});

If you would prefer to just patch scriptaculous instead, just include the following javascript after effect.js from scriptaculous is loaded (a default rails app can drop it into application.js).

Object.extend(Effect.Highlight.prototype, {
  finish: function() {
    this.element.style.background = "";
  }
});