Unobtrusive Image Mouseover

Using the following snippet of code to get an image with a mouseover image:

<%= image_tag(“button_off.png”, :mouseover => “button_on.png”, :alt => :button) %>

Generates inline JavaScript to do the image swapping like so:


It’s possible (and very simple) to do the image swapping in an UJS manner:


With the supporting jQuery snippet:


function() {

$(this).data(‘_mouseover’, $(this).attr(‘src’));

$(this).attr(‘src’, $(this).data(‘mouseover’));


function() {

$(this).attr(‘src’, $(this).data(‘_mouseover’));



Is there any specific reason I’m not aware of that Rails still uses inline JavaScript for this? Would there be any reception if I were to submit a pull request for this? Never contributed to rails before so I’m not sure. Thanks!

I don’t think you should change this. The reason it was done this way is to implement it in the easiest way possible, and that’s just adding two extra attributes and no supporting code.

Your way would require removing this behavior from Rails and implementing it in JS. You would have to contribute to both Rails and rails-ujs & prototype-ujs projects, because the latter implement behaviors around data-* attributes. I don’t think it’s too much work, but I think that you shuldn’t try to improve this. Ones who really care about properly doing image swapping will do so manually and handle advanced things like preloading of images.

I also don’t think there is any point implementing this particular feature “unobtrusively”, because in this context, “unobtrusive” has no meaning. If javascript is disabled in the user’s browser, there would be no difference in behavior between the “unobtrusive” and the current implementations.

-Steve Schwartz (@jangosteve)

Thanks for the input. That’s exactly what I needed to know.